digitaljoel
digitaljoel

Reputation: 26574

Allow caching with Spring MVC mvc:resources tag

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?

Upvotes: 6

Views: 7227

Answers (2)

Brian Clozel
Brian Clozel

Reputation: 59056

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

}

Upvotes: 3

madhead
madhead

Reputation: 33374

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>

Upvotes: 1

Related Questions