How to close a specific session in Java EE
How can I close a specific session if i have several session open as follows:
String userName = (String) session.getAttribute("userName");
HashMap cartList = (HashMap) session.getAttribute("cartList");
If i want to close the session of cartList, what code should i use?
I tried using the following:
session.invalidate()
but it closes everything.session.removeAttribute("cartList");
it didn't close my session.
You don't have several sessions open per visitor. You have only one session per visitor. You are just storing attributes in it. "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.
You seem to just want to unbind the shopping cart. The removeAttribute("name")
method is the right thing to do so. It will remove the attribute from the session, so that it's not accessible by getAttribute("name")
or ${name}
anymore in the current response and all subsequent requests/responses. That it apparently didn't work is likely just misconception from your side.
See also:
- How does
ServletContext
/HttpSession
/HttpServletRequest
/HttpServletResponse
work?
By
String userName = (String) session.getAttribute("userName");
HashMap cartList = (HashMap) session.getAttribute("cartList");
You aren't creating session by this, you are just reading attributes from the session referred by session
.
See
- HttpSession
session.invalidate()
will unbind all the objects which were bound to it while session.removeAttribute("cartList")
will unbind the cartList object from the session.
Try accessing
HashMap cartList = (HashMap) session.getAttribute("cartList");
after session.removeAttribute("cartList");
It will give you null in "cartList"
精彩评论