Suhail Gupta Suhail Gupta - 5 months ago 9
Java Question

How does isNew() tell if the session is a new one or is already in use?

How does calling

on the session object,check if the session is a new one or is already in use ?

I read that
isNew()
returns true if the client has not yet responded with the session ID. But what does it mean ? Please explain

Answer

I read that isNew() returns true if the client has not yet responded with the session ID. But what does it mean ?

Consider that the server is currently processing a request. There are two scenarios with respect to session handling.

  • In the new session scenario, a new session is being created for the user / client by the server. (The client may have supplied no session id in the request, or it may have supplied a session id that the server thinks is invalid.) The application code of the servlet decides a session is required (e.g. because it has some information it wants to store there), and attempts to fetch it with the "create if not present" flag. The servlet infrastructure realises that there is no current session, creates a new one with a new session id, and saves it in the session store. At the completion of the request, the session id is returned to the client; e.g. as a cookie, or as a URL with session id attached.

  • In the existing session scenario, the client has included a session id in the request; e.g. as a session cookie, or as a session id in the request URL. The servlet infrastructure recognizes this id, looks it up in its session store and (if necessary) recreates the HttpSession object containing the session state retrieved from the session store. When the application code of the servlet attempts to access the session, it gets this HttpSession object, not a new one. The session state can then be used and updated by the servlet as it processes the request.

In the first scenario, calling isNew() on the session object will return true because this is a new session.

In the second scenario, calling isNew() on the session object will return false because this is NOT a new session.

How does calling isNew() on the session object,check if the session is a new one or is already in use ?

The servlet infrastructure knows which of the two scenarios occurred because it did the session creation or session lookup. The most obvious implementation of isNew() is to include a private boolean field in the HttpSession object, and return the value of that field as the result of isNew(). The field would be initialized by the servlet infrastructure according to how it obtained the session object.