Using Sessions
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) { // No cart already in session
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
doSomethingWith(cart);
89
Servlets
www.corewebprogramming.com
HttpSession Methods
getAttribute, getValue [2.1]
Extracts a previously stored value from a session object.
Returns null if no value is associated with given name
setAttribute, putValue [2.1]
Associates a value with a name. Monitor changes: values
implement HttpSessionBindingListener.
removeAttribute, removeValue [2.1]
Removes values associated with name
getAttributeNames, getValueNames [2.1]
Returns names of all attributes in the session
getId
Returns the unique identifier
90
Servlets
www.corewebprogramming.com
45