title: Logout functionality using Servlets and Filters
body: <p>This is my filter code and the one below that is the <code>doPost()</code> method in my servlet.
  I'm trying to implement logout functionality. When logout button is clicked, control is sent to the servlet and it then redirects to my login page. However, I'm having a problem in that. The browser says <strong>The page is not redirecting properly</strong>. I have been going through all the questions in SO on this topic and nothing seems to help me out. I'm also having the back button problem which takes user back to a page even after logging out. Can someone explain what is that I'm doing wrong?</p>
  
  <p><strong>LogoutFilter.java</strong></p>
  
  <pre><code>public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
  
      HttpSession session = request.getSession(false);         
       if (session == null || session.getAttribute("loginUsername") == null) {
      response.sendRedirect("login.jsp"); // No logged-in user found, so redirect to login page.
  } else {
      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);
      chain.doFilter(req, res);  
  }
  }
  </code></pre>
  
  <p><strong>LogoutServlet.java</strong></p>
  
  <pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
              request.getSession().invalidate();
              RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
              rd.forward(request, response);
  
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> Also, when I type in a random url of a page from my project, it shows up without the user having to login. What to do to avoid that to happen?</p>
  
  <p><strong>UPDATE:</strong> I solved the random url page showing up problem by using some validations and redirecting to the login page accordingly. The logout functionality is working. However, when I press the back button it redirects to the login page itself(as required), BUT, one more press of the back button and the browser shows <strong>Document Expired</strong> message and if I press refresh, the secure page shows up again. Can anyone tell me what could be the problem here?</p>