How to effectively destroy 'session' in Java Servlet?

Sushan Ghimire picture Sushan Ghimire · Dec 20, 2012 · Viewed 90.4k times · Source

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.

Answer

BalusC picture BalusC · Dec 20, 2012

You need to 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 e.g. this answer.