Search code examples
javaservletshttpsession

Unable to Close my Session Servlets


I am unable to close my session using session.invalidate() in my logout method please help!

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    response.getWriter().println("<h3><a href='/assign2'>Logged out Successfully</a></h3>");
    HttpSession session = request.getSession(false);
    if(session!=null)
    session.invalidate();


}

the username does not get written to null at all

here's my welcome page to where i am redirecting it

HttpSession session=request.getSession(false);

    if(session!=null)
    {
        if((request.getSession().getServletContext().getAttribute("userid")) != null)
        {
            username = request.getSession().getServletContext().getAttribute("userid").toString();
        }

    }


    System.out.println(username);

Solution

  • The logoff page is OK, but in the welcome page you are mixing concepts:

    Altough the execution of session.invalidate does unbind all the bound attributes, you are retrieving attribute userid from the ServletContext, not the Session. Besides, note that request.getSession() creates a new session if necessary.

    The coherent way to store and retrieve attributes would be through the HttpSession object:

    HttpSession session=request.getSession(false);
    
    if(session!=null)
    {
        if((session.getAttribute("userid")) != null)
        {
            username = session.getAttribute("userid").toString();
        }
    }
    System.out.println(username);