Java Reference
In-Depth Information
If the fi rst version is used or the second version is used with an argument of
true , then the server returns the current session if there is one; otherwise, it creates
a new session object. For example:
HttpSession cart = request.getSession();
If the second version is used with an argument of false , then the current session
is returned if there is one, but null is returned otherwise.
A session object contains a set of name-value pairs. Each name is of type String
and each value is of type Object . Note that objects added to a session must imple-
ment the Serializable interface . (This is true for the String class and for the type
wrapper classes such as Integer .) A servlet may add information to a session object
via the following method:
void setAttribute(String <name>, Object <value>)
String currentProduct = request.getParameter("Product");
HttpSession cart = request.getSession();
The method to remove an item is removeAttribute , which has the following signature:
Object removeAttribute(String <name>)
For example:
To retrieve a value, use:
Object getAttribute(String <name>)
Note that a typecast will usually be necessary after retrieval. For example:
String product =
To get a list of all named values held, use:
String[] getAttributeNames()
For example:
String[] prodName = cart.getAttributeNames();
It's now time to put these individual pieces together into a full example
This example involves a simplifi ed shopping cart into which the user may place a
specifi ed weight of apples and/or a specifi ed weight of pears. Three servlets are
used, for the following purposes:
Search WWH ::

Custom Search