Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 474
Jaycee Avatar asked Apr 30 '26 08:04

Jaycee


1 Answers

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:

  • How do servlets work? Instantiation, sessions, shared variables and multithreading
like image 79
BalusC Avatar answered May 03 '26 14:05

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!