Java Tips & Tricks: Disabling Content Caching with Spring

Published Jun 15, 2015Last updated Mar 29, 2017

Have you ever checked some situation on your developed web application like, if you pressed the back button of your browser after logging in, what happened?

Well, if your web app was properly developed, you'd expect that it would redirect you to your after-logged-in-page (usually the Homepage) instead of showing the login form page.

However, the problem is that when you press the back button, your browser usually doesn't send another GET request to the server. Instead, it views the web page from locally cached responses. This is called browser caching/HTTP caching, it could happen not only in a login page, but in any page. This behavior is actually controlled by the Cache-Control header.

You can avoid this condition if you tell your browser not to cache the dynamic content. To do this, you'd have to write some cache-control header.

Well, in the Java Spring Framework, there is a very easy way to stop dynamic content caching. In your servlet context, just declare a bean WebContentInterceptor and define its properties.

        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/resources/**"/>
            <bean id="webContentInterceptor" 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"/>

Check servlet context declaration in details here.

The above-mentioned code is actually part of my crafted designed, Spring 4 Web Application Project Skeleton

Discover and read more posts from Abdullah Al Mamun Oronno
get started