3

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:

  1. session.invalidate() but it closes everything.
  2. session.removeAttribute("cartList"); it didn't close my session.
Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
newbie
  • 14,582
  • 31
  • 104
  • 146
  • Why do you want to close your sessions? Sessions should be managed closely read here => http://www.javapractices.com/topic/TopicAction.do;jsessionid=421CFEEA4A89B7C0709E070A8FA39C24?Id=191 You can remove the Cartlist attribute with removeAttribute in httpsession,Loosely speaking Session should be maintained throughout the login, and should be invalidated(destroyed) when user logs out. – Narayan Mar 17 '11 at 05:44

4 Answers4

6

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

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

jmj
  • 237,923
  • 42
  • 401
  • 438
2

session.invalidate() will unbind all the objects which were bound to it while session.removeAttribute("cartList") will unbind the cartList object from the session.

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
2

Try accessing

HashMap cartList = (HashMap) session.getAttribute("cartList");

after session.removeAttribute("cartList");

It will give you null in "cartList"

Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96