简体   繁体   English

如何使用Tomcat启用静态内容(images,css,js)的浏览器缓存?

[英]How to enable browser caching of static content(images, css, js) with Tomcat?

How to enable browser caching of static content(images, css, js) with Tomcat? 如何使用Tomcat启用静态内容(images,css,js)的浏览器缓存? Preferable solution will be editingspring MVC config files or web.xml 优选的解决方案是editingspring MVC配置文件或web.xml

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文档

If Spring 3.0 is being used, <mvc:resources> is one way to implement caching of static resources. 如果使用Spring 3.0, <mvc:resources>是实现静态资源缓存的一种方法。 This link has some documentation. 此链接有一些文档。

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());
    }

    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM