Search code examples
servletshttpsession

Can I delete a HttpSession manually in a servlet?


I took a JSP class and we learnt that we should always remove all the attributes of the HttpSession before we use it. So one of my classmate asked - "How about we delete the HttpSession permanently after we've done using it?"

So, my question is "can a HttpSession be deleted?"

From what I understand so far.... HttpSession is created by the servlet container, same as HttpServletRequest and HttpServletResponse. We get it through the HttpServletRequest, but we cannot delete it manully. Instead, there is timeout we can set to make the session end. Since we cannot delete it, we need to make sure we clean the session before we use it. Am I correct?

Thanks!


Solution

  • I took a JSP class and we learnt that we should always remove all the attributes of the HttpSession before we use it.

    If you mean this by manually using removeAttribute() for every single attribute which can be obtained by getAttributeNames(), then this makes really no sense. I'm not sure whether it's the course/tutor which is bad or that you misinterpreted the course/tutor.


    So one of my classmate asked - "How about we delete the HttpSession permanently after we've done using it?"

    Yes, you can "delete" it by invalidating it.

    session.invalidate();
    response.sendRedirect("login.jsp");
    

    Any subsequent request will force the server to create a new session. The redirect is by the way not necessary, but mandatory if you'd like to present the view in a fresh new session.

    See also: