The Java EE 5 Tutorial

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 =
        // 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). You can also notify objects of certain events related to their association with a session such as the following: