background image

Associating Objects with a Session

<< Maintaining Client State | Session Tracking >>
<< Maintaining Client State | Session Tracking >>

Associating Objects with a Session

Associating Objects 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 Associated with a Session
Recall that your application can notify web context and session listener objects of servlet
life-cycle events (
"Handling Servlet Life-Cycle Events" on page 103
). You can also notify objects
of certain events related to their association with a session such as the following:
When the object is added to or removed from a session. To receive this notification, your
object must implement the
javax.servlet.http.HttpSessionBindingListener
interface.
When the session to which the object is attached will be passivated or activated. A session
will be passivated or activated when it is moved between virtual machines or saved to and
restored from persistent storage. To receive this notification, your object must implement
the
javax.servlet.http.HttpSessionActivationListener
interface.
Session Management
Because there is no way for an HTTP client to signal that it no longer needs a session, each
session has an associated timeout so that its resources can be reclaimed. The timeout period can
be accessed by using a session's [get|set]MaxInactiveInterval methods.
Maintaining Client State
The Java EE 5 Tutorial · September 2007
126