Home TOC |
Search
Feedback |
Maintaining Client State
Many applications require a series of requests from a client to be associated with one another. For example, the Duke's Bookstore application saves the state of a user's shopping cart across requests. Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.
Accessing a Session
Sessions are represented by an HttpSession object. You access a session by calling the getSession method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, creates one. Since getSession may modify the response header (if cookies are the session tracking mechanism), it needs to be called before you retrieve a PrintWriter or ServletOutputStream.
Associating Attributes with a Session
You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session.
The Duke's Bookstore application stores a customer's shopping cart as a session attribute. This allows the shopping cart to be saved between requests and also allows cooperating servlets to access the cart. CatalogServlet adds items to the cart, ShowCartServlet displays, deletes items from, and clears the cart, and CashierServlet retrieves the total cost of the books in the cart.
public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();Notifying Objects That Are Added To a Session
Recall that your application can notify web context and session listener objects of servlet life cycle events (Monitoring Servlet Life Cycle Events). You can also notify objects of certain events related to their association with a session:
- When the object is added to or removed from a session. To receive this notification, your object must implement the javax.http.HttpSessionBindingListener interface.
- When the session to which the object is attached will be passivated and/or activated. A session will be passivated and activated when it is moved between VMs or saved to and restored from persistent storage. To receive this notification, your object must implement the javax.http.HttpSessionActivationListener interface.
Session Management
Since there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated time-out so that its resources can be reclaimed. The time-out period can be accessed with a session's [get|set]MaxInactiveInterval methods. You can also set the time-out period in deploytool:
To ensure that an active session is not timed-out, you should periodically access the session in service methods because this resets the session's time-to-live counter.
When a particular client interaction is finished, you use the session's invalidate method to delete a session on the server side. The session data is removed and when a new request is made to the servlet, a new session will be created.
The bookstore application's ReceiptServlet is the last servlet to access a client's session, so it has responsibility for invalidating the session:
public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); // Payment received -- invalidate the session session.invalidate(); ...Session Tracking
A web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and server. The main methods require the client to accept cookies or the web component to rewrite any URL that is returned to the client.
If your application makes use of session objects, you must ensure that session tracking is enabled by allowing the application to rewrite a URL 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.
The doGet method of ShowCartServlet encodes the three URLs at the bottom of the shopping cart display page as follows:
out.println("<p> <p><strong><a href=\"" + response.encodeURL(request.getContextPath() + "/catalog") + "\">Continue Shopping</a> " + "<a href=\"" + response.encodeURL(request.getContextPath() + "/cashier") + "\">Check Out</a> " + "<a href=\"" + response.encodeURL(request.getContextPath() + "/showcart?Clear=clear") + "\">Clear Cart</a></strong>");If cookies are turned off, the session is encoded in the Check Out URL as follows:
http://localhost:8080/bookstore1/cashier; jsessionid=c0o7fszeb1If cookies are turned on, the URL is simply:
http://localhost:8080/bookstore1/cashier
Home TOC |
Search
Feedback |