Most Java developers use HTTPSession to store the state. We know how to store it and invalid it. But we don’t think about how it works.

1. What is session and why do we need it?
A session is a series of requests to a servlet, originating from the same user at the same browser. Sessions allow applications running in a Web container to keep track of individual users. For example, a servlet might use sessions to provide “shopping carts” to online shoppers. Suppose the servlet is designed to record the items each shopper indicates he or she wants to purchase from the Web site. It is important that the servlet be able to associate incoming requests with particular shoppers. Otherwise, the servlet might mistakenly add Shopper_1’s choices to the cart of Shopper_2.
A servlet distinguishes users by their unique session IDs. The session ID arrives with each request. If the user’s browser is cookie-enabled, the session ID is stored as a cookie. As an alternative, the session ID can be conveyed to the servlet by URL rewriting, in which the session ID is appended to the URL of the servlet or JavaServer Pages (JSP) file from which the user is making requests. For requests over HTTPS or Secure Sockets Layer (SSL), Another alternative is to use SSL information to identify the session.

2. Session tracking options
There are several options for session tracking, depending on what sort of tracking method you want to use:
* Session tracking with cookies
* Session tracking with URL rewriting
* Session tracking with Secure Sockets Layer (SSL) information

3. Distributed sessions
Web applications often keep state in HTTP session attributes. Depending on the nature of your application, you may keep all your application state here or, perhaps, only login credentials and presentation state. Nonetheless, if you want a totally fault tolerant application, you need to make sure your web session state is replicated. Especially we want to use at load balance or clustering.
For example. Some wbe server (i.e WebSphere or JBoss) provides
* Database Session persistence
* Session replication
capable of replicating HTTP session state.

4. Best practices for using HTTP Sessions
* Release HttpSession objects using javax.servlet.http.HttpSession.invalidate method when finished.
* Avoid trying to save and reuse the HttpSession object outside of each servlet or JSP file.
* Implement the java.io.Serializable interface when developing new objects to be stored in the HTTP session.
More details can be found at reference.

Reference:
What is Session Tracking?

Using the HttpSession object of the Servlet API

Best practices for using HTTP Sessions

2 Ways To Implement Session Tracking

JBoss – HttpSession Replication

update: 2009-05-20
State replication in the Web tier

Advertisements