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 where 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.addHeader("Cache-Control", "no-cache");
  response.addDateHeader("Expires", 1);
%>

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.

Get Java Server Pages 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.