I've configured the Spring 3 MVC Dispatcher servlet at the root of my webapp, and using mvc:resources for serving static content as described in the docs: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-static-resources
Google's Chrome browser Audit tells me that the resources are explicitly non-cacheable. Here are the headers the same browser says is sent with the response:
Cache-Control:max-age=31556926, must-revalidate
Content-Length:1022
Content-Type:image/png
Date:Tue, 11 Jan 2011 00:20:07 GMT
Expires:Wed, 11 Jan 2012 06:08:53 GMT
Last-Modified:Mon, 29 Nov 2010 19:53:48 GMT
So, what do I need in order to make the resource cacheable?
Here is what you need to remember while caching static resources on CDN or local cache server: Use Cache-control HTTP directive to control who can cache the response, under which conditions, and for how long. Configure your server or application to send validation token Etag. Do not cache HTML in the browser.
The must-revalidate response directive indicates that the response can be stored in caches and can be reused while fresh. If the response becomes stale, it must be validated with the origin server before reuse. Typically, must-revalidate is used with max-age . Cache-Control: max-age=604800, must-revalidate.
We can enable caching in the Spring Boot application by using the annotation @EnableCaching. It is defined in org. springframework. cache.
Cache-control: max-age It is the maximum amount of time specified in the number of seconds. For example, max-age=90 means that a HTTP response remains in the browser as a cached copy for the next 90 seconds before it can be available for reuse.
As of Spring Framework 4.2, this is now fixed with more flexible Cache-Control
header values.
The "must-revalidate"
value is now disabled by default, and you can even write something like this:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/static/")
.setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS).cachePublic());
}
}
Maybe org.springframework.web.servlet.mvc.WebContentInterceptor can help you? Just add it to the list of interceptors:
<mvc:interceptors>
<bean class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheMappings">
<props>
<prop key="/ajax/promoCodes">300</prop>
<prop key="/ajax/options">0</prop>
</props>
</property>
</bean>
</mvc:interceptors>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With