Java Reference
In-Depth Information
connection is gone. 2 About the best one can hope for is that you'll use what,
in our postal analogy, would be like a supplied reply envelope. This allows the
servlet engine of the Web server to track requests from the same user and pro-
vide a session capability across requests. It will use your browsers cookie mecha-
nism to store this session's ID used to track your session. If you don't have
sessions on, it will need to use URL rewriting, whereby the URLs generated
will have an added parameter, the session ID.
Unlike the early days in the life of the Web, nowadays virtually everyone
has cookies enabled in their browsers—anyone who shops at amazon.com , at
least. This makes session tracking so much easier for the servlet developer. The
Web server handles all that automatically, and you only need to make a few
calls to the session-related methods of the HttpRequest .
To get a session for a user, ask for one from the HttpRequest :
HttpSession session = request.getSession(true);
The boolean parameter says whether ( true ) or not to create a session if
one does not yet exist for this user. Once you have a session, you can store
objects associated with that session:
session.setAttribute("cart", shopCart);
where shopCart is any serializable Object and "cart" could be any String
that you want to use to later identify and retrieve this object, for example:
Basket myCart = (Basket) session.getAttribute("cart");
Notice that we need to explicitly cast the object type returned by
getAttribute() , because it returns a generic Object .
18.6.1
For any information that you want to save for longer than the duration of a
session, you may want to investigate cookies—little bits of data (4K max; typi-
cally only a few bytes) sent to the browser for it to store and send back at a later
time. You make a cookie thus:
Cookies
2. You can go to another page, just be staring at the page for a long long time, or you might
have shut down your browser completely—and the server-side servlet will never know.
Search WWH ::




Custom Search