I just encountered the same problem, and found a good solution already provided by the framework. The org.springframework.web.servlet.mvc.WebContentInterceptor
class allows you to define default caching behaviour, plus path-specific overrides (with the same path-matcher behaviour used elsewhere). The steps for me were:
- Ensure my instance of
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
does not have the "cacheSeconds" property set.
Add an instance of 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>
After these changes, responses under /foo included headers to discourage caching, responses under /cache/me included headers to encourage caching, and responses under /cache/agnostic included no cache-related headers.
If using a pure Java configuration:
@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);
}
}
See also: http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…