Saturday, April 28, 2012

Prevent caching of JSP/Servlet output


In this example I will show you how to prevent caching of JSP/Servlet output using Cache-Control HTTP header.

Set Cache-Control header to prevent browser caching.

Browser caching can be disable by setting HTTP 1.1 Cache-Control header as shown below.
response.setHeader("Cache-Control", "no-cache");

Prevent caching of JSP output

Put following scriptlet at the beginning of the JSP to prevent output caching
<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevent caching at the proxy server
%>
it is always good to set Pragma header too, in case HTTP 1.0 is used.

Prevent caching of Servlet output

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  response.setHeader("Cache-Control","no-cache"); 
  response.setHeader("Pragma","no-cache");
  response.setDateHeader ("Expires", 0);
 
 }

No comments:

Post a Comment