servletsdestroyhttpsession

How to effectively destroy 'session' in Java Servlet?


The Servlet I'm working has a variable session.

I've tried session.invalidate();, this seem to have destroyed session but when I do a redirect like so response.sendRedirect("restanes.jsp");, it gives me HTTP Status 500 error with this line:

java.lang.IllegalStateException: getAttribute: Session already invalidated

This is expected since I was trying to destroy the session.

But why is the page unable to redirect? On the same page elsewhere I've redirected successfully.

How can I destroy session and redirect successfully?

Code snippet:

if(request.getParameter("logout") != null ){  
        session.invalidate();
        response.sendRedirect("restanes.jsp");
}

Update: All I needed to do was return; after response.sendRedirect("restanes.jsp");. Sincere thanks to BalusC.


Solution

  • Using sendRedirect() instead of forward() is indeed the solution. But you need to make sure you return from the method after sending the redirect.

    if (request.getParameter("logout") != null) {  
        session.invalidate();
        response.sendRedirect("restanes.jsp");
        return; // <--- Here.
    }
    

    Otherwise the code will continue to run and hit some session.getAttribute() method further down in the block causing exactly this exception. At least, that's the most likely cause of the problem described so far and based on the fact that this is a pretty common starter's mistake. See also among others java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed.