Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
Sushan Ghimire Avatar asked Dec 20 '12 00:12

Sushan Ghimire


People also ask

How would you destroy a session in servlet?

Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.

What servlet destroy () method is used for?

destroy. Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed.

How do you end a session in Java?

"Closing" a session happens by invalidate() method. It destroys the entire session and unbinds all of the attributes. Any next HTTP request will result in a fresh new session.

Which method destroys session object?

The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.


1 Answers

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.

like image 135
BalusC Avatar answered Sep 23 '22 07:09

BalusC