In JSP new session is created by default, if non present, so you will always get non null session. You can disable that by adding following page directive to your page:
<%@ page session="false" %>
JSPs create a session unless explicitly configured not to.Instead of checking for the existence of a session check for a value in the session.
When session calls invalidate() it removes that session from server context and all associated data with that session.When you make new request it creates new one and so you see null as the data because new session doesn’t have data in it
You should check for a logical attribute inside session to validate it user is logged in or not, instead of session itself
getSession(false) – will return current session if current session will not exist then it will NOT create new session.
Calling session.invalidate() removes the session from the registry. Calling getSession(false) afterwards will return null (note that getSession() or getSession(true) will create a new session in this case). In addition all session attributes bound to the session are removed. However if your code still has references to the session or any of its attributes then these will still be accessible:
if(request.getSession() != null) { System.out.println("Session is Created for Each Request with Unique Session ID"); } HttpSession session = request.getSession(); session.setAttribute("Name", "Mugil"); String Name = (String) session.getAttribute("Name"); System.out.println(session.getId()); System.out.println(session.getAttribute("Name")); session.invalidate(); if(session == null) { System.out.println("session is Null"); } if(request.getSession(false) == null) { System.out.println("request.getSession(false) is Null"); } if(request.getSession() != null) { System.out.println("request.getSession() is Not Null"); } System.out.println(session.getId()); System.out.println(Name);
Output
Session is Created for Each Request with Unique Session ID 7A46A65BCDC436030AA10385998F0272 Mugil request.getSession(false) is Null request.getSession() is Not Null 7A46A65BCDC436030AA10385998F0272 Mugil
Note
Session is created for each request. So if you are invalidating a session of login page in the next page you should check for existence of userName as session attribute instead of checking session is null because session can never be null