Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
9.2 The Session Tracking API
205
public void invalidate()
This method invalidates the session and unbinds all objects associated 
with it.
Associating Information with a Session
As discussed in the previous section, you read information associated with a
session by using 
getValue
 (in version 2.1 of the servlet specification) or
getAttribute
 (in version 2.2 ). To specify information in version 2.1 serv 
lets, you use 
putValue
, supplying a key and a value. Use 
setAttribute
 in
version 2.2. This is a more consistent name because it uses the 
get
/
set
 nota 
tion of JavaBeans. To let your values perform side effects when they are
stored in a session, simply have the object you are associating with the session
implement the 
HttpSessionBindingListener
 interface. Now, every time
putValue
 or 
setAttribute
 is called on one of those objects, its 
valueBound
method is called immediately afterward.
Be aware that 
putValue
 and 
setAttribute
 replace any previous values;
if you want to remove a value without supplying a replacement, use 
remove 
Value
 in version 2.1 and 
removeAttribute
 in version 2.2. These methods
trigger the 
valueUnbound
 method of any values that implement 
Http 
SessionBindingListener
. Sometimes you just want to replace previous
values; see the 
referringPage
 entry in the example below for an example.
Other times, you want to retrieve a previous value and augment it; for an
example, see the 
previousItems
 entry below. This example assumes a
ShoppingCart
 class with an 
addItem
 method to store items being ordered,
and a 
Catalog
 class with a static 
getItem
 method that returns an item, given
an item identifier. For an implementation, see Section 9.4 (An On Line Store
Using a Shopping Cart and Session Tracking).
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));
}
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved