Friday, November 04, 2005

How to disable browsers from caching web pages.

Caching is a feature that’s provided by most of the modern and intelligent browsers. But the convenience of caching affects standard behavior. Here is the question: what would a user see if after submitting a form he clicks Back browser button? Did you say that he would see the same form he just submitted with the same values filled in? Why? Because the browser saved the page in the cache in case it would be needed again?

Well, forget smart browsers and caching. How this is for you: each window or page in an interactive application is a View representing an application Model. In order for the View to be correct and consistent with the Model it must be rendered anew each time it is presented to the user.

In plain English: caching must be prohibited for web applications. Online books, dictionaries, pictures can be cached. But please dear browser, do not save snapshots of a live program, because they may not represent actual Model state anymore. It is bad if the saved View is just looked at, but it is tenfold worse when a stale View is used to modify the Model.

Now I ask the same question again: what would a user see if he clicks Back button after submitting a form? You know the correct answer already: the user of a well-designed web application would see a View which represents current Model state.

To disable browsers from caching web pages use the following caching tags in your JSP Page

meta http-equiv="pragma" content="no-cache"

meta http-equiv="cache-control" content="no-cache"

meta http-equiv="expires" content="0"

A page would be considered expired right after it loaded from the server.

If your network has a proxy server or firewall, the web pages will be cached on the proxy server. The browser cache-control would have no effect in the intermediate proxy server. And also browsers are not required to process cache control tags on the web pages, but they usually obey HTTP response header fields.

Hence if your JSP page with caching tags doesn’t work out you got to use HTTP response header fields. It is always advisable to use HTTP header fields to prevent caching.

response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Expires", "0");

response.setDateHeader("Expires", 0);

One more important point would be these header fields should always be added at the beginning of the JSP page before any processing happens.

Also take a look at this Link to learn more about META tags.


Post a Comment

<< Home