Creating a link to logout for JSP

38,338

Solution 1

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.

Solution 2

I found it easiest to do this:

<form method="link" action="logout.jsp">
    <input type="submit" value="Logout"/>
</form>

without logout.jsp having this:

<%
session.invalidate();
response.sendRedirect("startpage.html");
%>

Solution 3

Simplest way to do that is make a link of logout like this..

<a href="logout.jsp">LogOut</a>

And in the "logout.jsp" write below code

<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
Share:
38,338
Kelp
Author by

Kelp

Updated on April 02, 2020

Comments

  • Kelp
    Kelp about 4 years

    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?

  • Kelp
    Kelp over 13 years
    I tried that, but I get a 404 error. My servlet is mapped correctly in web.xml, and my link goes to that servlet.
  • BalusC
    BalusC over 13 years
    Then the URL is simply wrong :) Does it work when you enter it plain in browser address bar? Did you take the context path into account? Do you understand how relative URLs work?