3

I am trying to make a log out form in java and I am using cookies. But the problem is that when I hit the back button it redirects me to the last secured page witch I don't want.

Here is my code: servlet:

 @WebServlet(name="LogOut", urlPatterns={"/LogOut"})
public class LogOut extends HttpServlet {
 protected void doPost(HttpServletRequest req, HttpServletResponse response1)  
       throws ServletException, IOException {


    Cookie[] cookies = req.getCookies();
    if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookie.getName().equals(req.getSession().getAttribute("email"))){
            System.out.println( req.getSession().getAttribute("email") +cookie.getValue());
        }
        cookie.setMaxAge(0);
        response1.addCookie(cookie);
    }
    }
     //invalidate the session if exists
     HttpSession session = req.getSession(false);
     System.out.println("User="+req.getSession().getAttribute("email"));
     if(session != null){
        session.invalidate();
    }
     //no encoding because we have invalidated the session
     response1.sendRedirect("index.html");
 }
}



filter:



    @WebFilter("/NoCacheFilter")
public class NoCacheFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); //Proxies. 

        chain.doFilter(req, res);
    }
}

jsp:

<form action="logout" method="post">
                        <a><button type = "submit" class = "myprofile>Deconectare</button></a>
</form>

web.xml:

  <servlet>
    <servlet-name>logout</servlet-name>
    <servlet-class>user.LogOut</servlet-class>
 </servlet>
 <filter>
    <filter-name>nocachefilter</filter-name>
    <filter-class>user.NoCacheFilter</filter-class>
 </filter>
 <filter-mapping> 
   <filter-name>nocachefilter</filter-name>
   <url-pattern>/logout</url-pattern> 
</filter-mapping> 
<servlet-mapping>
    <servlet-name>logout</servlet-name>
    <url-pattern>/logout</url-pattern>
</servlet-mapping>

Could anyone help me?Thanks!

Bogdan
  • 155
  • 2
  • 3
  • 10

1 Answers1

0

The problem is that when you hit the back button, the page is loaded from the cache and not the browser. You can use the solution provided from this answer to avoid loading from the cache:

Prevent user from seeing previously visited secured page after logout

Your servlet and filter should be two different classes. In your case, you are using the same class as a Servlet and as Filter.

  <servlet-class>user.LogOut</servlet-class>
  <filter-class>user.LogOut</filter-class>

Create a Servlet class..and the cookie logic to that class.

   public class LogOutServlet extends HttpServlet{

        protected void doPost(HttpServletRequest req,
             HttpServletResponse response1) throws ServletException, IOException {
               Cookie[] cookies = req.getCookies();
              if (cookies != null) {
              for (Cookie cookie : cookies) {
                     if(cookie.getName().equals(req.getSession().getAttribute("email"))) {
                     System.out.println(req.getSession().getAttribute("email")
                        + cookie.getValue());
            }
            cookie.setMaxAge(0);
            response1.addCookie(cookie);
         }
    }
}

And your web.xml as : You have to specify the filter-mapping and servlet-mapping elements for each filter and servlet respectively. In you file, servlet-mapping was missing for logout servlet and filter-mapping was missing for filter.

 <servlet>
    <servlet-name>logout</servlet-name>
    <servlet-class>user.LogOut</servlet-class>
 </servlet>
 <filter>
    <filter-name>nocachefilter</filter-name>
    <filter-class>user.NoCacheFilter</filter-class>
 </filter>
 <filter-mapping> 
   <filter-name>nocachefilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping> 
<servlet-mapping>
    <servlet-name>logout</servlet-name>
    <url-pattern>/logout</url-pattern>
</servlet-mapping>
Community
  • 1
  • 1
  • When I am trying to implement like your example my whole program doesn't work. Err:'Starting Tomcat Server at localhost has encountered a problem.Server Tomcat Sever at local host failed to start'. – Bogdan Jun 23 '16 at 06:38
  • Did you make changes in the web.xml file properly ? What is the exception while starting the tomcat ? – Pooja Dubey Jun 23 '16 at 06:41
  • I have updated my question.Could you please take a look?Also my exceptions are:org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/e-health_nutrition]]; Caused by: java.lang.IllegalArgumentException: Invalid acasa.jsp in filter mapping – Bogdan Jun 23 '16 at 06:48
  • ` LogOutFilter user.LogOut LogOutFilter /logout logout user.LogOut logout /logout ` Can you try this ! Also , remove the annotations. Either use the web.xml mappings or the annotations ! – Pooja Dubey Jun 23 '16 at 07:02
  • I made the changes but how I call this filter in my jsp?
    I tried this but is not working: user.LogOut cannot be cast to javax.servlet.Servlet Also I Updated my question to see what I implemeted
    – Bogdan Jun 23 '16 at 07:10
  • Check the edited answer ! – Pooja Dubey Jun 23 '16 at 07:33
  • In the web.xml file what means ** ? user.LogOutServlet user.LogOut** – Bogdan Jun 23 '16 at 17:31
  • Check now ! Typing mistake it was. – Pooja Dubey Jun 24 '16 at 05:02
  • I have updated my code.Please check. Now I get the following error:SEVERE: Exception starting filter nocachefilter java.lang.ClassNotFoundException: user.NoCacheFiler Note: If I write the xml code as you said it gives me some errors. – Bogdan Jun 24 '16 at 06:19
  • can you show me your web.xml file – Pooja Dubey Jun 24 '16 at 06:23
  • Done!Sorry for dimension but I have a big app – Bogdan Jun 24 '16 at 06:27
  • check the updated answer..modify your web.xml as per that – Pooja Dubey Jun 24 '16 at 09:32
  • Now I have this problem : java.lang.ClassNotFoundException: user.NoCacheFiler , what should I do? – Bogdan Jun 24 '16 at 20:43
  • user.NoCacheFilter not user.noCacheFiler.. Spelling mistake it is. – Pooja Dubey Jun 25 '16 at 07:49
  • Now I am not getting errors.But it seems that this method is not working,because if I click logout and then the back button it returns me the last page(secured page) which I don't want. – Bogdan Jun 26 '16 at 16:54
  • Hi ! Is your problem solved ? If not , use this nocachefilter /* Change the url pattern of the filter, it should work – Pooja Dubey Jul 04 '16 at 10:41
  • I didn't solve the problem. When I added what you said I get some errors: Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/e-health_nutrition]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154) ... 6 more Caused by: java.lang.IllegalArgumentException: Filter mapping specifies an unknown filter name nocachefilter – Bogdan Jul 04 '16 at 14:44
  • Check the spelling in this line: user.NoCacheFiler Change it to **user.NoCacheFilter** – Pooja Dubey Jul 05 '16 at 06:26
  • I have edited my xml file, please take a look if it is ok! also is necessary to add logout user.LogOut logout /logout for my logout method or it will be called using the filter method? – Bogdan Jul 05 '16 at 08:15
  • It seems ok. Yes your logout servlet will be called by filter, but keep the servlet mapping element, just incase it be needed later. And please make sure the spelling of **user.NoCacheFilter** is correct in your xml. – Pooja Dubey Jul 05 '16 at 08:32
  • How can I apply the logout form only for one jsp page not for all? – Bogdan Jul 16 '16 at 11:57