JSP programming: session handling

http://javapapers.com/servlet/session-life-cycle/



Session Life Cycle

24/09/2009
When I say life cycle, I can hear you murmur “Oh no not again, how many life cycles I have to deal with”! In real world everything has life cycle, then why not in programming, after all, software is all about mimicking real life.  In a previous article I discussed about methods used for session tracking.
Frog Life Cycle
Frog Life Cycle
It has fundamental information about what a session is and how to manage it. At the end of that article I have given a preview about “5. Session tracking API”.
Now we are going to dive deep into it.
Just to recap, session is a conversion between a server and a client. An elite way to manage the session in servlets is to use API. Any web server supporting servlets will eventually have to implement the servlet API. It may or may not provide with more features of luxury but the minimum is guaranteed. Servlet specification ensures that, the minimum features provided make the session management job easier. Servlet API will use one of the underlying traditional mechanisms like cookies, URL rewriting, but that will happen behind the scenes and you need not worry about it!

How to access HttpSession object?

Every request is associated with an HttpSession object. It can be retrieved using getSession(boolean create) available in HttpServletRequest. It returns the current HttpSession associated with this request or, if there is no current session and create is true, and then returns a new session. A session can be uniquely identified using a unique identifier assigned to this session, which is called session id. getId() gives you the session id as String.
isNew() will be handy in quite a lot of situations. It returns true if the client does not know about the session or if the client chooses not to join the session. getCreationTime() returns the time when this session was created. getLastAccessedTime() returns the last time the client sent a request associated with this session.

How to store data in session?

Once you have got access to a session object, it can be used as a HashTable to store and retrieve values. It can be used to transport data between requests for the same user and session. setAttribute(String name, Object value) adds an object to the session, using the name specified. Primitive data types cannot be bound to the session.
An important note to you, session is not a bullock cart. It should be used sparingly for light weight objects. If you are in a situation where you have to store heavy weight objects in session, then you are in for a toss. Now it’s time to consult a software doctor. Your software design is having a big hole in it. HttpSession should be used for session management and not as a database.
Follow a proper naming convention to store data in session. Because it will overwrite the existing object if the name is same. One more thing to note is your object needs to implement Serializable interface if you are going to store it in session and carry it over across different web servers.

How to retrieve data from session?

getAttribute(String name) returns the object bound with the specified name in this session. Be careful while using this, most programmers fell into a deeply dug pit NullPointerException. Because it returns null if no object is bound under the name. Always ensure to handle null. Then, removeAttribute(String name) removes the object bound with the specified name from the session. Note a point; be cautious not to expose the session id to the user explicitly. It can be used to breach into another client’s session unethically.

How to invalidate a session object?

By default every web server will have a configuration set for expiry of session objects. Generally it will be some X seconds of inactivity. That is when the user has not sent any request to the server for the past X seconds then the session will expire. What do I mean by expire here. Will the browser blowup into colorful pieces? When a session expires, the HttpSession object and all the data it contains will be removed from the system. When the user sends a request after the session has expired, server will treat it as a new user and create a new session.
Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at logout. Or the application can have an absurd logic like after the user logins he can use the application for only 30 minutes. Then he will be forced out. In such scenario you can use getCreationTime().
Generally session object is not immortal because of the default configuration by the web server. Mostly these features are left to the imagination of web server implementers. If you take Apache Tomcat 5.5, there is an attribute maxInactiveInterval. A negative value for this will result in sessions never timing out and will be handy in many situations.
Long live the sessions!

An example servlet program to demonstrate the session API

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class SessionExample extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
 
// getting current HttpSession associated with this request or, if there
// is no current session and create is true, returns a new session.
HttpSession session = request.getSession(true);
 
// Calculating Hit Count
Integer count = (Integer) session
.getAttribute("SessionExample.HitCount");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("SessionExample.HitCount", count);
 
out.println("SessionExample");
out.println("

Example session servlet to "

+ "demostrate session tracking and life cycle");
 
// Displaying the hit count
out.println("Hit count for your current session is " + count);
 
out.println("

Some basic session information:

"
);
out.println("Session ID: " + session.getId() + "
"
);
out.println("Is it a new session: " + session.isNew() + "
"
);
out.println("Session Creation time: " + session.getCreationTime());
out.println("(" + new Date(session.getCreationTime()) + ")
"
);
out.println("Last accessed time: " + session.getLastAccessedTime());
out.println("(" + new Date(session.getLastAccessedTime()) + ")
"
);
out.println("Max in active time interval: "
+ session.getMaxInactiveInterval() + "
"
);
// Checks whether the requested session ID came in as a cookie
out.println("Session ID came in as a cookie: "
+ request.isRequestedSessionIdFromCookie() + "
"
);
 
out.println("

Iteratively printing all the values "

+ "associated with the session:");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value + "
"
);
}
 
out.println("");
}
}
Output of the example session servlet
Output of the example session servlet