J2EE Session Tracking
Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless in that every time a client sends a request, it opens a new connection and the HTTP server does not automatically maintains this conversational state of a user. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.
There are many use cases in which client conversational state has to be maintained over a series of HTTP requests. One of the most frequently used use case scenario is online shopping cart.
Session Tracking Mechanisms
So there are three different session tracking mechanisms -
(1) cookie based
(2) URL rewriting
(3) hidden form fields.
The first and second are used mostly frequently while the third is used rarely. Please not that these are just underlying mechanisms and do not provide any high-level programming APIs nor a framework for managing sessions. And as we will talk about again later on, this is where Servlet session tracking feature comes into the picture.
1- HTTP Cookies
Cookie is a small amount of information sent by a servlet to a Web browser. It is saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie’s value can uniquely identify a client. Server uses cookie’s value to extract information about the session from some location on the server
- Very easy to implement
- Highly customizable
- Persist across browser shut-downs
- Often: users turn off cookies for privacy or security reason
- Not quite universal browser support
2 – URL Rewriting
URLs can be rewritten or encoded to include session information. URL rewriting usually includes a session id. Session id can be sent as an added parameter:
http://.../servlet/Rewritten?sessionid=688
- Let user remain anonymous
- They are universally supported(most styles)
- Tedious to rewrite all URLs
- Only works for dynamically created documents
3 – Hidden Form Fields
Hidden form fields do not display in the browser, but can be sent back to the server by submit
<INPUT TYPE=”HIDDEN” NAME=”session” VALUE="...">
Fields can have identification (session id) or just some thing to remember (occupation). Servlet reads the fields using request.getParameter()
- Universally supported.
- Allow anonymous users
- Only works for a sequence of dynamically generated forms.
- Breaks down with static documents, emailed documents, bookmarked documents.
- No browser shutdowns.
Why do we need Session Tracking feature of Servlet?
Servlet programmers have to perform the following tasks themselves by using one of three session-tracking mechanisms.
- Generating and maintaining a session id for each session
- Passing session id to client via either cookie or URL
- Extracting session id information either from cookie or URL
- Creating and maintaining a hashtable in which session id and session information are stored
- Coming up with a scheme in which session information can be added or removed
Session Tracking Features of Servlet
- Provides higher-level API for session tracking
- Built on top of Cookie or URL rewriting
- Servlet container maintains
- Internal hashtable of session id’s
- Session information in the form of HttpSession
- Generates and maintains session id transparently
- Provides a simple API for adding and removing session information (attributes) to HttpSession
- Could automatically switch to URL rewriting if cookies are unsupported or explicitly disabled
Servlet Session Tracking Programming API
HttpSession is used to get a user’s existing or new session object:
HttpSession session = request.getSession(true);
“true” means the server should create a new session object if necessary. HttpSession is Java interface. Container creates a object of HttpSession type.
Example: Getting HttpSession Object
public class CatalogServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the user's session and shopping cart
HttpSession session =request.getSession(true);
...
out = response.getWriter();
...
}
}
...
HttpSession Java Interface Contains Methods to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time. Bind objects to sessions, allowing user information to persist across multiple user connections .
Store and Retrieve of Attribute
- To stores values:
- session.setAttribute(“cartItem”, cart);
- To retrieves values:
- session.getAttribute(“cartItem”);
Setting and Getting Attribute
public class CatalogServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getAttribute(
"examples.bookstore.cart");
// If the user has no cart, create a new one
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("examples.bookstore.cart", cart);
}
...
//see next slide.
}
}
How Servlet supports both Cookie-enabled and Cookie-disable browsers?
If your application makes use of session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
String response.encodeURL(URL)
Again, this method contains the logic to determine whether the session id needs to be encoded in the URL or not and then returns the URL with session ID if it is needed or URL without session ID otherwise. How does it decide? If browser supports cookies or session tracking is turned off, URL encoding is not necessary.
Example: response.encodeURL()
out.println("<p> <p><strong><a href=\"" +
response.encodeURL(request.getContextPath() + "/catalog") +
"\">" + messages.getString("ContinueShopping") +
"</a> " +
"<a href=\"" +
response.encodeURL(request.getContextPath() + "/cashier") +
"\">" + messages.getString("Checkout") +
"</a> " +
"<a href=\"" +
response.encodeURL(request.getContextPath() +
"/showcart?Clear=clear") +
"\">" + messages.getString("ClearCart") +
"</a></strong>");
Example: URL
- If cookies are turned off
- http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1
- If cookies are turned on
- http://localhost:8080/bookstore1/cashier
Session Timeout
Since there is no easy way for an HTTP client to signal the servlet that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed by the container. The timeout period can be accessed with a session’s [get|set]MaxInactiveInterval methods. You can also set the time-out period through vendor management tool. To ensure that an active session does not get timed out, you should periodically access the session via service methods because this resets the session’s time-to-live counter.
Since the number of “stale” session objects that are waiting to be timed out could be rather large, you are recommended to use the space in the Session object with care.
For example, if your web application handles 1000 users and if a user stays in average 2 minutes before leaving your application, and if your application saves 4K bytes of session data, the system would need 60Mbytes of memory just to maintain the session data and this is just for a single web application.
Related Posts
One Response to J2EE Session Tracking
Leave a Reply Cancel reply
Popular Posts (last 30 days)
- Attendance Management System 1483 view(s)
- Advanced Java Tutorial (For Intermediate) 762 view(s)
- JAVA Graphical User Interface (GUI) 723 view(s)
- Graph Implementation in C++ 534 view(s)
- File Handling using Input-Output Streams in Java 475 view(s)
- Linked lists in C++ 454 view(s)
- Sockets and Network Programming in Java 377 view(s)
- Applications of Stack in data structures 370 view(s)
- UDP Datagram Sockets in Java 361 view(s)
- Circular Linked Lists 332 view(s)








readers would be interested to note that it is a bad practice to store data in the session of a user as session attributes as it increases load on the application and is vulnerable. for more details see session tracking in java ee