A.9. Session Tracking

Looking Up Session Information: getValue

HttpSession session = request.getSession(true);
ShoppingCart cart =
  (ShoppingCart)session.getValue("shoppingCart");
if (cart == null) { // No cart already in session
  cart = new ShoppingCart();
  session.putValue("shoppingCart", cart);
}
doSomethingWith(cart);

Associating Information with a Session: putValue

 HttpSession session = request.getSession(true); session.putValue("referringPage", request.getHeader("Referer")); ShoppingCart cart = (ShoppingCart)session.getValue("previousItems"); if (cart == null) { // No cart already in session cart = new ShoppingCart(); session.putValue("previousItems", cart); } String itemID = request.getParameter("itemID"); if (itemID != null) { cart.addItem(Catalog.getItem(itemID)); ...

Get Core Servlets and JavaServer Pages™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.