22

I want to ensure that my servet's response is never cached by the broswer, such that even if two identical requests are made (a nanosecond apart), the server is always contacted. Is this the correct way to achieve this:

class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-cache");
    }
}

Thanks, Don

Dónal
  • 176,670
  • 166
  • 541
  • 787

3 Answers3

64

No, that's not the correct way. Here is the correct way:

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.

You'll probably see someone else suggesting other entries/attributes, but those are completely irrelevant when at least the above are mentioned.

Don't forget to clear your browser cache before testing after the change.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • In addition to before said, I would suggest to do this not in servlet, but in filter, placed before other filters/servlets, so that you can add no-caching to the whole application, without need to add or call this "response.set.." in each of servlets. – Illarion Kovalchuk Aug 05 '10 at 09:02
3

We use:

    // HTTP 1.1
    response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
    // HTTP 1.0
    response.setHeader("Pragma", "no-cache");
rsp
  • 22,242
  • 6
  • 51
  • 64
1

According to microsoft, these headers are required for IE:

  • Cache-Control;
  • Pragma;
  • Expires (that should be negative);

Example:

Pragma: no-cache
Cache-Control: no-cache
Expires: -1
alepuzio
  • 1,350
  • 2
  • 28
  • 36
Kurt Du Bois
  • 7,112
  • 4
  • 22
  • 32
  • But some clients need the longer list. Like java 1.7 applets. See http://stackoverflow.com/questions/17181129/java-1-7-applet-cacheentry-preventing-dynamic-updates – flup Aug 08 '14 at 11:25