Preventing Caching of JSP Pages

A browser can cache web pages so that it doesn’t have to get them from the server every time the user asks for them. Proxy servers can also cache pages that are frequently requested by all users going through the proxy. Caching helps cut down the network traffic and server load, and provides the user with faster responses. But caching can also cause problems in a web application in which you really want the user to see the latest version of a dynamically generated page.

Both browsers and proxy servers can be told not to cache a page by setting response headers. You can use a scriptlet like this in your JSP pages to set these headers:

<%
  response.addHeader("Pragma", "no-cache");
  response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  response.addHeader("Cache-Control", "pre-check=0, post-check=0");
  response.setDateHeader("Expires", 0);
%>

An alternative is to use a custom action that’s included with the book examples:

<%@ taglib uri="orataglib" prefix="ora" %>
<ora:noCache/>

The <ora:noCache> action sets the exact same headers as the scriptlet example, but it’s cleaner.

The reason so many headers are needed is that different browsers and proxies respect different headers. The Pragma header is intended for old HTTP/1.0 clients. According to the HTTP/1. 0 specification, this header is really a request header but proxies and some browsers are known to respect it even when it’s used as a response header. The Cache-Control header is an HTTP/1.1 ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.