Session management

  • Http protocol makes use of stateless connections for scalability. That means the server cannot remember clients between requests.
  • In J2EE World, the servlet container generates a unique session ID on client’s request and gives it back to client along with the response. The client sends that sessionID with each subsequent request. The container identifies the client by seeing the sessionID, finds the matching session and associates the session with the request.
  • The client and container exchange the session information through cookies. The container sends a “set-cookie” header in the response. When the client makes subsequent request, it sends “Cookie” header in the request.
  • The container handles all the cookie work and you as a developer do not need to worry about it. The only thing you as a developer need to worry about is to tell the container that you want to create or use a session. The container handles the rest of the work like creating session ID, creating a new cookie, stuffing the sessionID  into the cookie and setting the cookie as part of the response header.

How do you send the session Cookie in a RESPONSE?

HttpSession session = request.getSession():

As soon as you say this in your service method, every thing happens automatically for you. The above code does just more than creating a session. When you invoke it the first time, it will send a cookie in the response. You do not do any of the following

  • Do not make the new HttpSession object.
  • do not generate unique session ID.
  • Do not make a new cookie Object
  • Do not stuff the sessionID into the cookie Object
  • Do not set the cookie into the response.

How do you get the Session ID from the REQUEST?

HttpSession session = request.getSession();

If the received request has a session ID cookie, the container finds the matching session using the included session ID. Otherwise, it will create a new session.

How do you know if there was a session already?

You use the function of the session as syntaxed below


This method returns “true” if the container cannot find a session ID or matching session ID in the request.

Overloaded getSession method

There is another overload method called request.getSession(boolean). If you set the parameter of this method to false, you will either get a null or a pre-existing session. If the method runs null, you can create a new session if you want.

Passing Boolean value true to that method is same as request.getSession() described in the above parts of this blog.

URL Rewriting to make sessions work

If the cookies are disabled in the browser, the above mentioned methods will not work as the client will never join the session implying that the session.isNew() method always return true. In this situation, you can use URL rewriting.

In URL rewriting, the sessionID that is otherwise stuff with in the cookie , is now appended to the end of the URL that comes into this app.

The container always uses cookie approach first and if it fails, it uses URL rewriting to accomplish sessions.  Container accomplishes URL rewriting only if you as a developer have done the job of encoding all the URLs you send in the response. The syntax for it is


By encoding as mentioned above, the container adds extra session ID info to the above URL. You can also redirect the request to different URL , but want to use the same session, you can use response.encodeRedirectURL(“/”).

Important points to remember:

  • You can use URL rewriting only if all the pages that are part of the session are dynamically generated.
  • URL rewriting is done in a vendor specific way. Tomcat us a semicolon to append session ID to the URL.
  • URLRewriting is handled by response object.

Important methods of HttpSession:

  • getCreationTime(): returns the session creation time.
  • getLastAccessedTime(): returns the last time the container got a request  with this session ID
  • setMaxInactiveInterval(): Maximum time in seconds allowed between requests in the session
  • getMaxInactiveInterval(): returns maximum time  in seconds that is allowed between requests for this session
  • invalidate(): Concludes the session. Unbinds all the session attributes currently in the session

How do you set session time out?

The container gets rid of all the pale sessions. The session can die because of time out or call to invalidate() on the session or the  browser or computer crashes.

Open web.xmal and paste the following to make session die after 15 minutes of being idle






You can also set session time out for a specific session with out effecting the time out length for any other session in the web application using session.setMaxInactiveInterval(15*60);

Other uses of cookies:

  • Cookies can be used to exchange name/value pairs between client and server. The server sends the cookie to the client and the client in turn will send the cookie back to server with each subsequent request.  Session cookies are vanished when the client browser quits. There is a way to tell the cookie to persist on the client even after the browser shuts down. Using this way, the web application can still get the cookie information even though the session with client was expire long back

Getting Cookie Information using Servlet API:

  • You can get all the information you need to know about cookies using HttpServletRequest, HttpServletResponse and Cookie classes of Servlet API

Cookie Code:

  • Creating a new cookie

Cookie cookie = new Cookie(“userName”, name);

  • Sending the cookie to the client


  • Setting how long acookie will live on the client

Cookie.setMaxAge(time in seconds).

Setting max age to -1 makes the cookie disappear when the browser closes.

  • Getting cookie form the client request

Cookie[] cookie = request.getCookies();

For(int i=0;i<cookie.length; i++){

Cookie cookie = cookie[i];


String username= cookie.getValue();





Some points worth knowing regarding HTTP Session

  • You do not configure HttpSessionBindingListner in deployment descriptor as it is not related to session on whole. It is to let the object used as attribute to know if it is bound or unbound to session. The object should implement HttpSessionBindingListener.
  • In a distributed application there may be multiple JVMs’ which may or may not be on same physical servers and so the app is in multiple places. So during load balancing, the same client requests could end up going to different instances of the same servlet. In such situations, the following things happen to ServletContext, ServletConfig and HttpSession.

ServletContext:There are multiple contexts @ one context per VM

ServletConfig: There are multiple configs as well @ one ServletConfig perServlet per VM

HttpSessionObject: Only one HttpSession on all the VMs’ combined. HttpSessions along with their attributes move from one VM to another

  • Servlet specs do not dictate the container vendor to support clustering. How an app server handles clustering is completely at the mercy of the vendor.
  • Sessions upon migrating from one VM to other do not leave its trace. It is passivated on the VM it existed before moving to another VM in which it is activated. There is a slight delay or latency using this process.
  • HttpSessionActivationListener prepares attributes to move from one VM to another which means the attributes should ready their instance variables for serialization.
  • If some of the attribute instance variables are not serializable, use  activation/passivation call back methods to prepare them for serialization so that the state exists as it used to be in the previous VM before migrating to the new VM. (user writeObject () and readObject() methods)
  • HttpSessionEvent has getSession method to get the current session where as HttpSessionBindingEvent has getName() which returns name of the attribute, getValue() which returns the object in addition to getSession method.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s