© Copyright Marcus Green 2007

Chapter 4) Session Management

1) Storing objects in sessions

4.1) Write servlet code to store objects into a session object and retrieve objects from a session object.

What is a session?

HTTP (the HyperText Transfer Protocol) is at the heart of the World Wide Web and one of its essential features is that it is “stateless”. This means that when a web browser makes a request for a resource from a web server, the server “forgets” about the requesting machine at the end of the transaction. The benefit of this is that a server can be relatively simple and can serve up vast amounts of information without having to track each machine between requests.

This gives a big performance advantage by comparison with technologies that require a user to log in and for the server to “maintain state”. However it comes with the significant disadvantage that HTTP does not support a continuous conversation, i.e. each request is treated in isolation to every other request. This means it is not possible to design a shopping cart system in “pure HTTP” because although you could request an item from a page displaying inventory, as soon as you made the next request the server would not know about your previous request.

If it was not possible to overcome this inherent problem the World Wide Web would be a footnote in the history of technology. The standard way of maintaining state between an individual web browser and a web server is the concept of a session. There are several ways of creating a session but different web programming technologies (ASP, JSP, PHP) all use a very similar approach. To become familiar with using sessions you have to forget most what you might know about using standard Java variables (fields and method local variables) and get used to using session based attributes. Once you become familiar with session based attributes you can mostly forget that they require a session to sustain state.

Servlet Sessions

When a web browser makes a request from the server the server generates a unique id that is returned to the browser. An example of a unique id might look something like

6AD095E84932FFD37E02CA74870CE71D

The browser then stores this id and upon making the next request the id is sent to the server so it can associate each successive request. The most common way of storing this “conversational state” is for the server to generate a cookie or a small piece of text that is transmitted with the header information of the page returned to the browser. Cookie technology was invented by Netscape corporation, one of the first very popular browsers in the early days of the web.

The JSESSIONID cookie (SRV.7.1.1)

The servlet specification mandates that the cookie used to maintain sessions be called JSESSIONID. It is perfectly possible to maintain state by hand coding your own state by writing code to manually store and retrieve cookies. Having done that task myself using the Perl programming language I recommend you be grateful for the servlet session mechanism and never try to maintain state through your own code.

When cookies are used for maintaining a session it must be called JSESSIONID.



Some users have had concerns that cookies bring privacy issues, but they are generally benign and bring the huge benefit of allowing a browser to establish a session with a server. If a browser has cookies disabled or does not support cookies it is possible to record the state by a process known as URL re-writing where the unique id is appended to the browser URL, which can thus be read by the server. This is covered in more detail in section 4.4.

Using sessions with JSP pages is fairly transparent as by default JSP pages are session enabled and provide the implicit session object, which can be manipulated via scriptlets, beans and EL code. A session does not automatically die when a user shuts down their browser, but is dependent on the session timeout (see section 4.2). Using sessions within servlets requires more direct programmer intervention. Once your system has the session configured you can store objects of any data type within a session attribute in a similar way you store objects in a “plain old Java program”.

The HttpSession interface

According to the Sun API documentation the HttpSession interface

Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. “

Servlet code can obtain a session by calling the getSession method thus if the following servlet is run, it will store the value of the parameter username in the session and print it out with subsequent requests to the page.

/**
 * How to use session tracking
 * with the HttpServlet interace
 * Marcus Green 2006
 ***/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
String sUserName;
 protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
   PrintWriter out = response.getWriter();
   HttpSession session = request.getSession();
   sUserName = request.getParameter("username");
   if(sUserName ==null){
      String sUserName = (String) session.getAttribute("username");
   }else{
     session.setAttribute("username",sUserName);
   }
   out.print("UserName="+session.getAttribute("username")) ;
 }
}

setAttribute and getAttribute

As illustrated in the previous example the methods for storing and retrieving objects in a session are setAttribute and getAttribute. These work in the way that attributes were explained in section 3.2, the difference being that the objects are available as long as the session lasts and from any servlet taking part in the session. Note that attribute data is stored with a type of Object and must be cast back to the required type before being used. As should be implied from this, an attribute cannot be a primitive type.


Other sources

Maintaining client state by Sun
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Servlets11.html#wp64744

Session tracking by Marty Hall
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Session-Tracking.html

API Docs to the HttpSession interface
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html

Cookies according to Wikipedia
http://en.wikipedia.org/wiki/HTTP_cookie

According to Mikalai Zaikin
http://java.boot.by/wcd-guide/ch04.html#c4s1