在基于注解的 Spring MVC Controller 中,为特定路径设置缓存头的首选方法是什么?
最佳答案
我刚遇到同样的问题,发现框架已经提供了一个很好的解决方案。 org.springframework.web.servlet.mvc.WebContentInterceptor
类允许您定义默认缓存行为,以及特定于路径的覆盖(与其他地方使用的相同路径匹配器行为)。我的步骤是:
- 确保我的
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
实例没有设置“cacheSeconds”属性。 添加一个
WebContentInterceptor
的实例:<mvc:interceptors> ... <bean class="org.springframework.web.servlet.mvc.WebContentInterceptor" p:cacheSeconds="0" p:alwaysUseFullPath="true" > <property name="cacheMappings"> <props> <!-- cache for one month --> <prop key="/cache/me/**">2592000</prop> <!-- don't set cache headers --> <prop key="/cache/agnostic/**">-1</prop> </props> </property> </bean> ... </mvc:interceptors>
在这些更改之后,/foo 下的响应包含不鼓励缓存的 header ,/cache/me 下的响应包含鼓励缓存的 header ,而/cache/agnostic 下的响应不包含与缓存相关的 header 。
如果使用纯 Java 配置:
@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/* Time, in seconds, to have the browser cache static resources (one week). */
private static final int BROWSER_CACHE_CONTROL = 604800;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/images/**")
.addResourceLocations("/images/")
.setCachePeriod(BROWSER_CACHE_CONTROL);
}
}
另请参阅:http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html
关于java - 如何在 Spring MVC 中设置缓存 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1362930/