How to check whether the session is existed?
There are two ways to detect whether the session is existed.
1) request.getSession(); + session.isNew()
- Retrieve a session from “request.getSession();”, this function will always return a session no matter what, it’s equivalent to request.getSession(true);. The only problem is you do not know whether this is new or existed session.
- Later you can check with “session.isNew()”, true if this is a new session else return an existed session.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("New session is jutst created"); }else{ pw.println("This is old session"); } }
2) request.getSession(false); + if(session ==null)
- Retrieve a session from “request.getSession(false);”, this function will return a session if existed , else a null value will return.
- Later you can do a “null” checking with the session object, null means no existed session available.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(false); if(session ==null){ pw.println("No session available"); }else{ pw.println("This is old session"); } }