4

How can I stop caching of pages in browser using Servlets?

I want that session should expire if I press back button of browser when i am logged in.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Prashant
  • 61
  • 1
  • 1
  • 2
  • possible duplicate of [Restrict user from the previous page after signout.](http://stackoverflow.com/questions/4194207/restrict-user-from-the-previous-page-after-signout) – BalusC Feb 28 '11 at 11:59

2 Answers2

10

To permanently disable cache.

  // Set to expire far in the past.
  response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

  // Set standard HTTP/1.1 no-cache headers.
  response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

  // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
  response.addHeader("Cache-Control", "post-check=0, pre-check=0");

  // Set standard HTTP/1.0 no-cache header.
  response.setHeader("Pragma", "no-cache");

Clearing the client cache would not expire session immediately,but clears session cookies in the browser. To make the session expire immediately, you need to explicitly specify in server side jsp or servlet.

// use session invalidate
session.invalidate();
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
2

If you get a HttpServletResponse (implementation) object for the request you can send HTTP headers that will encourage browsers not to cache the content you send them.

HttpServletResponse response; // You'll need to initialize this properly

response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");

See the documentation for HttpServletResponse and HttpServletResponseWrapper. In case you need to read up on cache control headers in HTTP, check this out.

A. R. Younce
  • 1,913
  • 17
  • 22