How to prevent a JSP/Sevlet output page from being cached by the browser?

Sometimes we faced the caching problem of Internet Explorer. Some of the pages of any site were unable to show the updated data because the browser displays the old cached pages stored in the memory. There are couple of solutions to prevent browser caching-
JavaScript solution- If the url of the page which we don’t want to be cached becomes unique every time, then browser treats those pages as new pages every time and doesn’t cache them. So whenever there is link to this page we can use JavaScript time function to append a unique time variable after the url of the page. Below is the source of the JavaScript:
                                                                       


function time()
{
            var hhmmss = new Date();
            var hh= hhmmss.getHours();
            var mm= hhmmss.getMinutes();
            var ss= hhmmss.getSeconds();
            var timeval = hh*10000+mm*100+ss;
            return timeval;
}                                                                                                                     
function printPreview() {
       var forwardPage = “displayresults.jsp”+“?”+time();
       var printPageStyle =    “status=no,menubars=no,scrollbars=yes,resize=no,
left=60,top=40,width=700,height=450″;
       window.open(forwardPage, printPageStyle);
}
The first JavaScript generates a unique string based on the current time and the next JavaScript opens a print preview page by appending the unique string at the end of the URL to be opened. This will always generate a new link and browser will not cache this.
Java Solution- Developer needs to set the HTTP headers in order to prevent the browser to cache the jsp pages or servlet output. The code snippet is given below:
<%
response.setHeader(“Cache-Control“,”no-store”);
response.setHeader(“Pragma\“,”no-cache”);
response.setDateHeader (“Expires“, 0);
//prevents caching at the proxy server
%>
This scriplet should be placed at the very start of the Jsp pages and in servlet before outputting the content.
So, happy coding and provide me your feedback. Do post your comments if you’ve any questions. I’ll reply you back.

TechcubeTalk Staff

This post/article/tutorial is written and published by TechCubeTalk.com staff (Blog editors, paid contributors or a guest contributors). TechCubeTalk.com reserves all rights and no part of this article can be published anywhere without prior written permission.