How to effectively destroy 'session' in Java Servlet?

帅比萌擦擦* 提交于 2019-12-18 11:21:50

问题


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.


回答1:


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.




回答2:


Your code is okay

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

but make sure the redirecting page does not contain any session attributes. 500 internal error coming from "restanes.jsp" page. work out with the redirected page and session activity.



来源:https://stackoverflow.com/questions/13963720/how-to-effectively-destroy-session-in-java-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!