Search code examples
javajspauthenticationservletsforms-authentication

Creating a link to logout for JSP


when a user logins to my application, he submits a form to be processed through the Servlet. The servlet creates a session for the user. How would I create a link so the user can logout? I cannot seem to directly link to a Servlet. How would I delete the session and link back to the homepage?

Here is a way that I could do it, but it doesn't seem "right". I could link back to the index.jsp?logout=true. My index.jsp will see if logout is true and delete the sessions.

Is there another way to do it?


Solution

  • Write a servlet mapped to /logout which then executes something like this in doGet:

    HttpSession session = request.getSession(false);
    if(session != null)
        session.invalidate();
    request.getRequestDispatcher("/index.jsp").forward(request,response);
    

    It wont matter if the user has a session or not, they will ultimately be redirected to index.jsp.