14

I opened the session in my servlet when the user performed a successful login:

HttpSession session = request.getSession(true);
session.setAttribute("name", name);

then I wrote in the logout.jsp to terminate the session:

<%session.invalidate();%>

To check if a session is valid I am doing this:

HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");

But it is not working, I am getting the session valid even after the session.invalidate. Does anyone understand where am I doing wrong?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Noah Martin
  • 1,708
  • 9
  • 35
  • 73
  • Looks like already answered: http://stackoverflow.com/questions/4899500/jsf-logout-using-session-invalidate-does-not-clear-the-current-username – Alex Kreutznaer Jan 21 '13 at 18:39
  • no it does not answer to my problem, I am talking jsp/servlets and not jsf tags. at the other hand I want to know what problem do I have in my code – Noah Martin Jan 21 '13 at 18:43
  • The idea is the same, you should redirect the request to a new page, than the container will finally invalidate your old session. – Alex Kreutznaer Jan 21 '13 at 18:47

2 Answers2

26

you should call session.getSession(false) - which returns null if there is no current session.

according to docs

HttpSession#getSession(boolean create) - create - true to create a new session for this request if necessary; false to return null if there's no current session.

So the correct way of session value check would -

HttpSession session = request.getSession(false);
if(session!=null)
  session.setAttribute("name", name);

and once you invalidate the session -

HttpSession session = request.getSession(false);
if(session!=null)
session.invalidate();
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
-1

To Validate the Session

HttpSession session = request.getSession(true);
session.setAttribute("name", name);

To invalidate it you need to do

session.removeAttribute("name");
session.invalidate();

But you need to keep one thing in mind that the object may became invalid but this doesnot mean that it will cleaned immediately, even after invalidating it after all its attributes gone it is possible that sesssion object will get reused, I got the same user ID and creation time.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
myk.
  • 323
  • 1
  • 5