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

时间:2010-11-08 11:18:55

标签: java spring caching tomcat spring-mvc

如何使用Tomcat启用静态内容(images,css,js)的浏览器缓存? 优选的解决方案是editingspring MVC配置文件或web.xml

3 个答案:

答案 0 :(得分:23)

尝试(改变值)

<mvc:resources mapping="/static/**" location="/public-resources/" 
       cache-period="31556926"/>
<mvc:annotation-driven/>

你也可以使用拦截器:

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

请参阅MVC docs

答案 1 :(得分:1)

如果使用Spring 3.0,<mvc:resources>是实现静态资源缓存的一种方法。 This link有一些文档。

答案 2 :(得分:0)

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:

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

    // ...
}