How to clear browser cache from servlet?

25,621

Solution 1

You cannot clear the cache, but you can ask that your pages will not be cached. This means that you must do so for every page in your session (else the back-button will keep working, and your logout page is the only page not cached).

See also: How to control cache in JSP page?:

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.

edit: Apparently it is possible to clear the cache programmatically using javascript and a refresh, but I doubt that this is what you are looking for: How to programmatically empty browser cache?

Solution 2

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

//Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-store");

//Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0);

//Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma", "no-cache");
//HTTP 1.0 backward enter code here

String userName = (String) session.getAttribute("plno");
if (null == userName) {
  //request.setAttribute("Error", "Session has ended.  Please logenter code herein.");
  RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
  rd.include(request, response);
  out.println("Session has ended.  Please login.");
}
%>

This is how to clear the cache in jsp page. It can also set the session's inactive timeout

Share:
25,621
Hareesh
Author by

Hareesh

Java Devoloper

Updated on May 12, 2020

Comments

  • Hareesh
    Hareesh almost 4 years

    When I'm clicking logout button I want the browser cache to be cleared.

    I'm trying to clear the browser cache, using the following code:

    if(uri.equals("/SciArchive/logout.sci"))
        {
            HttpSession session=req.getSession(false);
             res.setHeader("Cache-Control","no-cache"); 
                 res.setHeader("Cache-Control","no-store"); 
                 res.setDateHeader("Expires", 0); 
                 res.setHeader("Pragma","no-cache"); 
            if(session!=null)
            {
                session.invalidate();
                rd=req.getRequestDispatcher("/home.jsp");               
            }
    
            rd.forward(req,res);
            return;
        }
    

    When back button is pressed in browser window after logout, I need the browser not showing the previous page.

    When I'm clicking back button it shows the previous page, after clicking forward button in browser window it shows document expired.

    Please give me suggestions to clear this error!

  • blackbird
    blackbird almost 10 years
    What do you mean by "this is the way"?