December 14, 2004: caching and webapplications

Are you dealing with caching of the webpages of your j2ee application or do you think it is not an issue? Than you likely end with an angry client that at some point is confronted with the data of somebody else on his screen.
This is caused by the caching of webpages (http respons) somewhere between the browser and the application. What happens is that when a (cache) server receives a request, it looks in its cache to see if it contains a matching and still valid response. If that is the case it returns that response without even sending the request to the application. With static webpages this is a completely valid action but with dynamic web applications a request often results in consulting and procedding server-side data and therefore needs it to be executed and not to be cached. In this case the returning of a cached response may result in sending old data to the client or even presenting him with data from somebody else. Most of the time it is not possible to be involved with the configuration of the cache server, so one need to take care of it in the application. Fortunately this is possible.
An http request and response contains a header and a body. The body can be considered the page, the header can be considered as meta data for the page. The page is displayed by the browser, the headers are used for routing and interpretation.
A few of these header items influence the caching of the response. So, when a response should not be cached these headers must be added to the response:

Cache-control: no-cache
Pragma: no-cache
expiration: THU, 01 Jan 1970 00:00:00 GMT

The first is for HTTP/1.1, the second for HTTP/1.0 as is the third, which is also added to prevent caching with older browsers.
A j2ee application offers many options for adding these headers to the response, like jsp's, servlet's, Filters etc... This is easily done with the following code:

response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);

Struts has an excellent configuration option: <controller nocache="true" ></controller> . This setting adds the three mentioned headers to the response and still allows you to override it in the application.
Posted by Aino at 10:55