Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
202
Chapter 9 Session Tracking
Looking Up the HttpSession Object Associated
with the Current Request
You look up the
HttpSession
object by calling the
getSession
method of
HttpServletRequest
. Behind the scenes, the system extracts a user ID
from a cookie or attached URL data, then uses that as a key into a table of
previously created
HttpSession
objects. But this is all done transparently to
the programmer: you just call
getSession
. If
getSession
returns
null
, this
means that the user is not already participating in a session, so you can create
a new session. Creating a new session in this case is so commonly done that
there is an option to automatically create a new session if one doesn't already
exist. Just pass
true
to
getSession
. Thus, your first step usually looks like
this:
HttpSession session = request.getSession(true);
If you care whether the session existed previously or is newly created, you
can use
isNew
to check.
Looking Up Information Associated with a
Session
HttpSession
objects live on the server; they're just automatically associated
with the client by a behind the scenes mechanism like cookies or
URL rewriting. These session objects have a built in data structure that lets
you store any number of keys and associated values. In version 2.1 and earlier
of the servlet API, you use
session.getValue("attribute")
to look up a
previously stored value. The return type is
Object
, so you have to do a type
cast to whatever more specific type of data was associated with that attribute
name in the session. The return value is
null
if there is no such attribute, so
you need to check for
null
before calling methods on objects associated with
sessions.
In version 2.2 of the servlet API,
getValue
is deprecated in favor of
get
Attribute
because of the better naming match with
setAttribute
(in ver
sion 2.1 the match for
getValue
is
putValue
, not
setValue
). Nevertheless,
since not all commercial servlet engines yet support version 2.2, I'll use
getValue
in my examples.
Here's a representative example, assuming
ShoppingCart
is some class
you've defined to store information on items being purchased (for an imple
mentation, see Section 9.4 (An On Line Store Using a Shopping Cart and
Session Tracking)).
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
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