如何在Spring Boot中将Cache-Control标头添加到静态资源中?

2022-09-01 14:06:54

如何在Spring Boot中为静态资源添加HTTP标头?Cache-Control

尝试在应用程序中使用筛选器组件,该组件可以正确写入标头,但标头被覆盖。Cache-Control

@Component
public class CacheBustingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 
                                              throws IOException, ServletException {

        HttpServletResponse httpResp = (HttpServletResponse) resp;
        httpResp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        httpResp.setHeader("This-Header-Is-Set", "no-cache, no-store, must-revalidate");
        httpResp.setHeader("Expires", "0");

        chain.doFilter(req, resp);
    }

我在浏览器中得到的是:

Cache-Control:no-store
This-Header-Is-Set:no-cache, no-store, must-revalidate
Expires:0

我想要的是:

Cache-Control:no-cache, no-store, must-revalidate
This-Header-Is-Set:no-cache, no-store, must-revalidate
Expires:0

答案 1

发生这种情况是因为Spring Security:它重写所有缓存标头以完全禁用缓存。因此,我们需要做两件事:

  1. 禁用静态资源的弹簧安全性
  2. 启用静态资源缓存处理

在当前版本的Spring Boot中,我们可以在appsage.properties config中更改此行为。

禁用某些资源的弹簧安全性:

# Comma-separated list of paths to exclude from the default secured 
security.ignored=/myAssets/**

为静态资源启用发送缓存标头:

# Enable HTML5 application cache manifest rewriting.
spring.resources.chain.html-application-cache=true

# Enable the Spring Resource Handling chain. Disabled by default unless at least one strategy has been enabled.
spring.resources.chain.enabled=true
# Enable the content Version Strategy.
spring.resources.chain.strategy.content.enabled=true 
# Comma-separated list of patterns to apply to the Version Strategy.
spring.resources.chain.strategy.content.paths=/** 

# Locations of static resources.
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

就这样。现在,Spring将检查您的静态文件是否已更改,并且可以发送更智能的响应(If-Modiffied-Since等),并重写您的appcache。

此外,如果有理由不对某些资源使用基于内容的版本 - 您可以使用备用的 FixedVersion 策略并在配置中显式设置版本:

#Enable the fixed Version Strategy.
spring.resources.chain.strategy.fixed.enabled=false 
# Comma-separated list of patterns to apply to the Version Strategy.
spring.resources.chain.strategy.fixed.paths= 
# Version string to use for the Version Strategy.
spring.resources.chain.strategy.fixed.version= 

在文档中查看更多内容


答案 2

根据文档,.这很容易。(我现在没有与之相关的代码。ResourceHandlerRegistry

在配置静态资源的地方,只需添加方法,它将返回对象。addResourceHandlerResourceHandlerRegistration

在那里,您可以使用setCacheControl方法。您要做的是配置并设置一个 CacheControl obejct。

这是从春季4.2开始的,否则你将不得不像下面这样做。

@Configuration
@EnableWebMvc
@ComponentScan("my.packages.here")
public class WebConfig extends WebMvcConfigurerAdapter {


   @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").setCachePeriod(0);
    }

}

推荐