views:

301

answers:

2

How do you add an Expires or a Cache-Control Header in JSP. I want to add a far-future expiration date in an include page for my static components such as images, css and .js files.

Any help is appreciated.

+1  A: 
<%
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
%>
Darin Dimitrov
+2  A: 

To disable browser cache JSP pages, create a Filter which is mapped on an url-pattern of *.jsp and does basically the following in the doFilter() method:

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache", "no-store", "must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.

This way you don't need to copypaste this over all JSP pages and clutter them with scriptlets.

To enable browser cache for static components like CSS and JS, put them all in a common folder like /static and create a Filter which is mapped on an url-pattern of /static/* and does basically the following in the doFilter() method:

httpResponse.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // 1 week in future.

See also:

BalusC
+∞ if I could for your blog post link. It saved me SO. MANY. HOURS.
Matt Ball
@Bears: You're welcome :)
BalusC