Saturday, June 7, 2008

Session Tracking in Servlets - How do we do it?

Session Tracking in Servlets

Servlets use the interface HttpSession
to maintain sessions. This interface helps identifying a user during various page requests by storing information about that user.

The process is pretty simple in case of servlets - it just looks for an already existing session object for the current request and if it find then it simply uses the information stored in that session object otherwise if it's the first request then it creates a new session object. Sessions are also Java objects only and hence the process of retrieval or add/update of information is very simple. The HttpSession interface provies various methods to interact with the session object.

The beauty of the HttpSession objects is that the servlet writer doesn't need to bother about whether the browser is supporting cookies or not as the servlet internally handles this either by creating and maintaining cookies, if supported, otherwise it automatically uses URL-Rewriting approach (Read more about all the session tracking mechanism here). These HttpSession objects live on the server and ther are just automatically associated with the client requests either with the help of Cookies or URL-Rewriting.

Example: creating and using HttpSession objects

HTTPSession httpSession = request.getSession(true);
UserCredentials userCredentials = (UserCredentials) httpSession.getValue("userCredentials");
if(userCredentials != null) {
//... use the credentials to authenticate the user
} else {
//... create userCredentials and store into the session


'request.getSession(true)' first tries to get the HttpSession object associated with the request and if not found (in case it's the first request) then 'true' parameter causes a new HttpSession object to be created and associated. We normally pass 'true' only as the parameter to the getSession() method as in absence of an HttpSession you would anyway like to create a new session. You can always check using isNew() method whether it's a new session or an existing one.

Any addition/deletion of an object in/from an HttpSession object is first checked whether that object implements the HttpSessionBindingListener interface or not. If the object being added or deleted is found to have implemented this interface then the underlying servlet notifies the object that it has been bound (when added to the session) to OR unbound (when deleted from the session) from the session.

If the cookies are intentionally turned off that means the clinet doesn't want to join a session and in such a case the servlet simply creates different session objects for different requests, which indirectly serves the purpose of the client. In such a case, the isNew() method of the HttpSession object will always return 'true'.


No comments: