brite, a MVC Framework for jQuery

Java: Servlet Set Expires Header with Cache Control

March 28th, 2009 by jeremychone

When 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);

4 Responses to “Java: Servlet Set Expires Header with Cache Control”

  1. Reno Says:

    Or use a framework like Spring MVC and write the conf:

  2. jeremychone Says:

    @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.

  3. Matt Says:

    awesome, very useful, thanks!

  4. Sushant Says:

    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

Leave a Reply