Monday, August 18, 2014

Add cache control headers to Spring MVC

Many times we want browsers and proxies and gateways to cache our static files. But not the data calls. Here's how to add cache control headers in Spring MVC. 

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- Cache of HTML pages -->
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/images/**"  />
            <mvc:exclude-mapping path="/webjars/**"  />
            <bean
                    class="org.springframework.web.servlet.mvc.WebContentInterceptor">
                <property name="cacheSeconds" value="0"/>
                <property name="useExpiresHeader" value="true"/>
                <property name="useCacheControlHeader" value="true"/>
                <property name="useCacheControlNoStore" value="true"/>
            </bean>
        </mvc:interceptor>

        <!-- Cache of all images  -->
        <mvc:interceptor>
            <mvc:mapping path="/images/**"/>
            <bean
                    class="org.springframework.web.servlet.mvc.WebContentInterceptor">
                <property name="cacheSeconds" value="1800" />
                <property name="useExpiresHeader" value="true"/>
                <property name="useCacheControlHeader" value="true"/>
                <property name="useCacheControlNoStore" value="true"/>
            </bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/webjars/**"/>
            <bean
                    class="org.springframework.web.servlet.mvc.WebContentInterceptor">
                <property name="cacheSeconds" value="86400" />
                <property name="useExpiresHeader" value="true"/>
                <property name="useCacheControlHeader" value="true"/>
                <property name="useCacheControlNoStore" value="true"/>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>



This will create the below HTTP headers:

Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache
Cache-Control: no-store

This should take care of all the cache problems that we have.

No comments:

Post a Comment