如何在Spring Boot中将Cache-Control标头添加到静态资源中? [英] How to add Cache-Control header to static resource in Spring Boot?
问题描述
如何在Spring Boot中为静态资源添加 Cache-Control
HTTP标头?
How can I add Cache-Control
HTTP header in Spring Boot for static resources?
尝试在应用程序中使用过滤器组件,该组件可以正确写入标头,但 Cache-Control
标头会被覆盖
Tried using a filter-component in the application, which writes headers correctly, but Cache-Control
header gets overwritten.
@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);
}
我在浏览器中看到的是:
What I get in the browser is:
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
推荐答案
按照 ResourceHandlerRegistry 的ResourceHandlerRegistry.html rel = noreferrer>文档。这很容易。 (我现在没有与此相关的代码。)
As per the documentation, of ResourceHandlerRegistry
. It is pretty easy. (I have no code related to it right now.)
在配置静态资源的地方,只需添加 addResourceHandler
方法,它将返回 ResourceHandlerRegistration
对象。
In the place where you configure your static resources just add addResourceHandler
method, It will return ResourceHandlerRegistration
object.
您可以使用 setCacheControl 方法。您要做的就是配置并设置 CacheControl 对象。
There you can use setCacheControl method. What you have to do is configure and set a CacheControl obejct.
这是自4.2春季以来,否则您将必须像下面那样进行操作。
This is since spring 4.2, else you will have to do it like below.
@Configuration
@EnableWebMvc
@ComponentScan("my.packages.here")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").setCachePeriod(0);
}
}
这篇关于如何在Spring Boot中将Cache-Control标头添加到静态资源中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!