java 如何使用 Tomcat 启用静态内容(图像、css、js)的浏览器缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4123324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enable browser caching of static content(images, css, js) with Tomcat?
提问by yura
How to enable browser caching of static content(images, css, js) with Tomcat? Preferable solution will be editingspring MVC config files or web.xml
如何使用 Tomcat 启用静态内容(图像、css、js)的浏览器缓存?优选的解决方案是编辑spring MVC 配置文件或web.xml
回答by Bozho
try (with changing the values)
尝试(改变值)
<mvc:resources mapping="/static/**" location="/public-resources/"
cache-period="31556926"/>
<mvc:annotation-driven/>
You can also use an interceptor:
您还可以使用拦截器:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/static/*"/>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="31556926"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
See the MVC docs
查看MVC 文档
回答by Raghuram
回答by bsiamionau
For those who use Java configuration, you can manage caching parameters using ResourceHandlerRegistry
, there is example how do I set up different caching preferences for different content types:
对于那些使用 Java 配置的人,您可以使用 管理缓存参数ResourceHandlerRegistry
,有示例如何为不同的内容类型设置不同的缓存首选项:
@Configuration
@EnableWebMvc
// ...
public class WebConfiguration extends WebMvcConfigurerAdapter {
// ...
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/ui/css/**")
.addResourceLocations("classpath:/WEB-INF/css/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
registry.addResourceHandler("/ui/js/**")
.addResourceLocations("classpath:/WEB-INF/js/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
registry.addResourceHandler("/ui/**")
.addResourceLocations("classpath:/WEB-INF/")
.setCacheControl(CacheControl.noCache());
}
// ...
}