Monday, April 26, 2010

Session Life Cycle

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.

import java.io.IOException;
02.import java.io.PrintWriter;
03.import java.util.Date;
04.import java.util.Enumeration;
05.
06.import javax.servlet.ServletException;
07.import javax.servlet.http.HttpServlet;
08.import javax.servlet.http.HttpServletRequest;
09.import javax.servlet.http.HttpServletResponse;
10.import javax.servlet.http.HttpSession;
11.
12.public class SessionExample extends HttpServlet {
13.
14.public void doGet(HttpServletRequest request, HttpServletResponse response)
15.throws ServletException, IOException {
16.response.setContentType("text/html");
17.PrintWriter out = response.getWriter();
18.
19.// getting current HttpSession associated with this request or, if there
20.// is no current session and create is true, returns a new session.
21.HttpSession session = request.getSession(true);
22.
23.// Calculating Hit Count
24.Integer count = (Integer) session
25..getAttribute("SessionExample.HitCount");
26.if (count == null)
27.count = new Integer(1);
28.else
29.count = new Integer(count.intValue() + 1);
30.session.setAttribute("SessionExample.HitCount", count);
31.
32.out.println("<-HTML><-HEAD><-TITLE>SessionExample<-/TITLE><-/HEAD>");
33.out.println("<-BODY>Example session servlet to "
34.+ "demostrate session tracking and life cycle");
35.
36.// Displaying the hit count
37.out.println("Hit count for your current session is " + count);
38.
39.out.println("Some basic session information:");
40.out.println("Session ID: " + session.getId() + "<-/BR>");
41.out.println("Is it a new session: " + session.isNew() + "<-/BR>");
42.out.println("Session Creation time: " + session.getCreationTime());
43.out.println("(" + new Date(session.getCreationTime()) + ")<-/BR>");
44.out.println("Last accessed time: " + session.getLastAccessedTime());
45.out.println("(" + new Date(session.getLastAccessedTime()) + ")<-/BR>");
46.out.println("Max in active time interval: "
47.+ session.getMaxInactiveInterval() + "<-/BR>");
48.// Checks whether the requested session ID came in as a cookie
49.out.println("Session ID came in as a cookie: "
50.+ request.isRequestedSessionIdFromCookie() + "<-/BR>");
51.
52.out.println("<-H2>Iteratively printing all the values "
53.+ "associated with the session:<-/H2>");
54.Enumeration names = session.getAttributeNames();
55.while (names.hasMoreElements()) {
56.String name = (String) names.nextElement();
57.String value = session.getAttribute(name).toString();
58.out.println(name + " = " + value + "<-/BR>");
59.}
60.
61.out.println("<-/BODY><-/HTML>");
62.}
63.}

No comments: