Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an Expires or a Cache-Control header in JSP

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 JavaScript files.

like image 755
Sam Avatar asked Jun 16 '10 16:06

Sam


People also ask

How do I add cache-control headers?

To use Cache-Control headers, choose Content Management | Cache Control Directives in the administration server. Then, using the Resource Picker, choose the directory where you want to set the headers. After setting the headers, click 'OK'.

What is cache-control HTTP header?

Cache-control is an HTTP header used to specify browser caching policies in both client requests and server responses. Policies include how a resource is cached, where it's cached and its maximum age before expiring (i.e., time to live).

What is expire cache?

When the Expires date is equal to the Date header value, the response is considered to be expired. When a response has an Expires header field with a date/time that is in the future, then that response is considered "cacheable". Servers should not set an Expires date that is more than one year in the future.

What is incomplete or no cache-control header set?

The cache-control header has not been set properly or is missing, allowing the browser and proxies to cache content.


1 Answers

To disable browser cache for 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 or /resources and create a Filter which is mapped on an url-pattern of /static/* or /resources/* and does basically the following in the doFilter() method:

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

See also:

  • Making sure a web page is not cached, across all browsers.
  • Webapplication performance tips and tricks.
like image 185
BalusC Avatar answered Sep 27 '22 00:09

BalusC