Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate/invalidate sessions jsp/servlets?

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?

like image 490
Noah Martin Avatar asked Jan 21 '13 18:01

Noah Martin


People also ask

How do you check if a session is invalidated or not?

2 Answers. Show activity on this post. HttpSession session = request. getSession(false); if (session == null || !

How check session is valid or not in JSP?

Before to check session's attributes, you have to see the session itself. So, first: HttpSession session = request. getSession(false); if(session !=

How do you invalidate a session in a servlet?

To invalidate a session manually, call the following method: session. invalidate();


1 Answers

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();
like image 185
Subhrajyoti Majumder Avatar answered Sep 20 '22 07:09

Subhrajyoti Majumder