How to Disable Browser Caching

In some web-app can be useful avoid browser caching of pages. This implies that a new request is needed every time a page is loaded.
Basically there are three ways to do this:
  • using HTML code
  • defining a Java Filter on wanted URL
  • if you are using SPring Framework, defining an Interceptor

HTML

The effect can be achieved by using meta tags in the HTML header:

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">

The Cache-Control header was added in HTTP 1.1, while the other two were also present in HTTP 1.0.

Java Filter

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(request, response);

The configuration of web.xml should looks like this:

<!-- MyServler -->
<servlet>
	<servlet-name>myServlet</servlet-name>
	<servlet-class>mypackage.MyServlet</servlet-class>
</servlet>     
<servlet-mapping>
	<servlet-name>myServlet</servlet-name>
	<url-pattern>/path</url-pattern>
</servlet-mapping>

<!-- MyFilter -->
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>mypackage.MyFilter</filter-class>
    <init-param>
        <param-name>pattern</param-name>
        <param-value>{{PATTERN HERE}}</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/path</url-pattern>
</filter-mapping>

Spring MVC

In Spring MVC, you can create an interceptor like so:

public class DisableBrowserCachingInterceptor extends HandlerInterceptorAdapter {

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
        response.setDateHeader("Expires", 0); // Proxies
    }
}

A handler interceptor is registered to the DefaultAnnotationHandlerMapping bean, which is charged with applying interceptors to any class marked with a @Controller annotation.
You can specify multiple interceptors in the interceptors property, whose type is an array.

<beans ...>
...
	<bean id="measurementInterceptor" class="com.apress.springrecipes.court.web.MeasurementInterceptor" />
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<property name="interceptors">
		   <list>
		     <ref bean="measurementInterceptor" />
		   </list>
		</property>
		...
	</bean>
</beans>

If you want to learn more retro games news, read our magazine and subscribe to our newsletter.