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
.
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.
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.
"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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With