Mark Needham

Thoughts on Software Development

Tomcat – No caching of RESTlet resources for Firefox

with 3 comments

One problem that we’ve been trying to solve today is how to make a RESTlet resource non cacheable.

The reason for this is that when a user logs out of the system and then hits the back button they shouldn’t be able to see that page, but instead should see the login form.

After several hours of trawling Google and trying out various different suggestions we came across the idea of setting ‘cache-control’ with the value ‘no-store’ in the response headers.

The code to make this happen is as follows (use inside a class which extends Resource):

1
2
3
HttpResponse response = (HttpResponse) getResponse();
Series<Parameter> headers = response.getHttpCall().getResponseHeaders();
headers.add("cache-control", "no-store");

The important part in this example is the last line. As long as it’s added to the Http Response Headers that response should no longer be cached.

A bit of research revealed that Internet Explorer may change the ‘no-store’ value to ‘no-cache’ so I’m not sure if this will work for that browser.

Written by Mark Needham

October 22nd, 2008 at 10:00 pm

Posted in Java

Tagged with , ,

  • Darren Hobbs

    There is a standard incantation for persuading web caches not to cache your stuff. You need more than what you’ve currently got. This should cover most flavours of proxy and web browser:

        private void invokeTheCachePreventionIncantation(HttpServletResponse response) {
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); //HTTP 1.1
            // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache"); //HTTP 1.0
            response.setDateHeader("Expires", 0); //prevents caching at the proxy server
        }
    
  • Darren Hobbs

    Sorry, also forgot to add that for the definitive guide to HTTP caching (and probably way more than you ever wanted to know about HTTP!) Check out this section of the HTTP spec.

  • http://www.markhneedham.com Mark Needham

    Ah cool, good to know.

    ‘Cache-Control’, ‘no-cache’ and
    ‘Pragma’, ‘no-cache’

    seem to already be set by RESTlet by default. I didn’t know about the other ones though.

    Thanks, Mark