2

I am trying to cache the servlet response but somehow it is not working (Firebug is giving me 200 OK each time i refresh the page). This is the code I added in the servlet:

response.setContentType("application/javascript");
long now = System.currentTimeMillis();
response.setCharacterEncoding("UTF-8");
response.setDateHeader("Last-Modified", 0);
response.addHeader("Cache-Control", "max-age=5184000");
response.setDateHeader("Expires", now + 5184000 * 1000);
response.addHeader("Vary", "Host");

I've also tried with setHeader and with Last-Modified, now.

Nothing seems to work. Any ideas?

Thanks

This is how firebug shows me the response/request headers (when the resource should have been fetched from cache but isnt):

 Response Headersview source
 Cache-Control  max-age=5184000
 Connection Keep-Alive
 Content-Type   application/javascript;charset=UTF-8
 Date   Thu, 21 Mar 2013 09:53:48 GMT
 Expires    Sun, 31 Mar 2013 16:51:01 GMT
 Keep-Alive timeout=15, max=99



 Request Headersview source
 Accept */*
 Accept-Encoding    gzip, deflate
 Accept-Language    en-US,en;q=0.5
 Cache-Control  max-age=0
Iulia Muntianu
  • 145
  • 1
  • 14

1 Answers1

5

Using Last-Modified requires cooperative coding in your servlet. When you send it to a client, that client will then send back, when requesting the same resource, one of a possible set of headers:

  • If-Modified-Since:
  • If-Unmodified-Since:

You would have to process these headers, determine if the content had changed since the given date and then send a 304 response if it hadn't. Lots of manual work. Also note that the Last-Modified date has to be valid (e.g: Tue, 15 Nov 1994 12:45:26 GMT).

The simplest route for you would be to ignore Last-Modified for now, and instead use the Cache-Control and Expires headers. Your Expires header needs to be in a valid date format, as described for the Last-Modified header.

You can read up more on caching in general, in this excellent document.

Community
  • 1
  • 1
Perception
  • 79,279
  • 19
  • 185
  • 195