Java: Servlet Set Expires Header with Cache Control
March 28th, 2009 by jeremychoneWhen setting the expires date in Servlet, better to set the cache-control as well.
final int CACHE_DURATION_IN_SECOND = 60 * 60 * 24 * 2; // 2 days
final long CACHE_DURATION_IN_MS = CACHE_DURATION_IN_SECOND * 1000;
long now = System.currentTimeMillis();
//res being the HttpServletResponse of the request
res.addHeader("Cache-Control", "max-age=" + CACHE_DURATION_IN_SECOND);
res.addHeader("Cache-Control", "must-revalidate");//optional
res.setDateHeader("Last-Modified", now);
res.setDateHeader("Expires", now + CACHE_DURATION_IN_MS);
For no cache
res.setHeader("Pragma", "No-cache");
res.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
res.setDateHeader("Expires", 1);
April 7th, 2009 at 8:01 am
Or use a framework like Spring MVC and write the conf:
…
April 7th, 2009 at 5:29 pm
@Reno I am a big fan of Spring IOC, but not of Spring MVC. Spring MVC is too heavy/constraining for Web application. It focuses too much on the controller piece and does not decouple enough the Model, View and Action. But for developers that like to write XML Config files, then, Spring MVC is definitely a nice solution.
April 5th, 2010 at 4:49 pm
awesome, very useful, thanks!
February 24th, 2011 at 3:36 pm
I tried adding these, still my FF browser does not cache the response on browser. I am able to verify this using FireBug.
This is how my HTTP Response Header looks -
Response Headersview source
Server Apache-Coyote/1.1
Cache-Control max-age=300, must-revalidate
Last-Modified Thu, 24 Feb 2011 22:05:06 GMT
Expires Thu, 24 Feb 2011 22:10:06 GMT
Content-Length 279
Date Thu, 24 Feb 2011 22:05:06 GMT