Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
9.2 The Session Tracking API
203
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);
In most cases, you have a specific attribute name in mind and want to find
the value (if any) already associated with that name. However, you can also
discover all the attribute names in a given session by calling 
getValueNames
,
which returns an array of strings. This method is your only option for finding
attribute names in version 2.1, but in servlet engines supporting version 2.2
of the servlet specification, you can use 
getAttributeNames
. That method is
more consistent in that it returns an 
Enumeration
, just like the 
getHeader 
Names
 and 
getParameterNames
 methods of 
HttpServletRequest
. 
Although the data that was explicitly associated with a session is the part
you care most about, there are some other pieces of information that are
sometimes useful as well. Here is a summary of the methods available in the
HttpSession
 class.
public Object getValue(String name)
public Object getAttribute(String name)
These methods extract a previously stored value from a session object. 
They return 
null
 if there is no value associated with the given name. Use 
getValue
 in version 2.1 of the servlet API. Version 2.2 supports both 
methods, but 
getAttribute
 is preferred and 
getValue
 is deprecated.
public void putValue(String name, Object value)
public void setAttribute(String name, Object value)
These methods associate a value with a name. Use 
putValue
 with 
version 2.1 servlets and either 
setAttribute
 (preferred) or 
putValue
(deprecated) with version 2.2 servlets. If the object supplied to 
putValue
 or 
setAttribute
 implements the 
HttpSessionBinding 
Listener
 interface, the object's 
valueBound
 method is called after it is 
stored in the session. Similarly, if the previous value implements 
HttpSessionBindingListener
, its 
valueUnbound
 method is called.
public void removeValue(String name)
public void removeAttribute(String name)
These methods remove any values associated with the designated name. 
If the value being removed implements 
HttpSessionBindingLis 
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