Servlets provide an outstanding technical solution:
the HttpSession
API. This is a high-level interface
that allows the server to "remember" a set of information relevant
to a particular user's on-going transaction,
so that it can retrieve this information to handle any future requests
from the same user. Roughly, this is how you can use HttpSession
:
Whenever you need to remember some information about what
the user does, you start a new HttpSession
and attach (or store) the information to this session.
Then behind the scene, your Tomcat server will assign a unique "session id"
to the session and send this id to the browser, asking the browser to
send back the id in any future requests. This way, the Tomcat server will
be able to trace the requests coming from the same user,
and let you retrieve whatever has been stored to handle the
user's requests.
The servlet HttpSession
uses one of two mechanisms to
ask the browser to remember and send back the session id in future
requests: Cookies or URL rewriting.
If the user's browser supports cookies, the Tomcat server will ask the
browser to store the session id in cookies.
In case the browser does not support cookies or
the user explicitly disabled it, the server
reverts to URL-rewriting by appending the session id to the end of
every URL. All these details are handled by the
HttpSession
automatically and hidden from the application developer.
getSession
method
of HttpServletRequest
.
If this returns null, you can create
a new session, but this is so commonly done that there
is an option to automatically create a new session if there
isn't one already. Just pass true
to getSession
.
Thus, your first step usually looks like this:
HttpSession session = request.getSession(true);
HttpSession
objects live on the server;
they're just automatically associated with the requester by
a behind-the-scenes mechanism like cookies or URL-rewriting.
These session objects have a built-in data structure that let
you store and retrieve any number of keys and associated values.
You can use getAttribute("key")
to look up a previously
stored value. The return type is Object
, so you have
to do a typecast to whatever more specific type of data was associated
with that key in the session. The return value is null
if there is no such attribute.
You can use setAttribute("key", value)
to store any value
for the key, where the value can be any Java object.
Here's one representative example, assuming ShoppingCart
is some
class you've defined yourself that stores information on items being
purchased.
HttpSession session = request.getSession(true);In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling
ShoppingCart previousItems =
(ShoppingCart)session.getAttribute("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}
getAttributeNames
, which returns
an Enumeration
of all attribute names.
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.
true
if the client
(browser) has never seen
the session, usually because it was just created rather than being
referenced by an incoming client request. It returns false
for preexisting
sessions. Date
constructor or the setTimeInMillis
method
of GregorianCalendar
. getAttribute
.
To specify information, you use setAttribute
, supplying a
key and a value. Note that setAttribute
replaces any
previous values. Sometimes
that's what you want (as with the referringPage
entry in the example below),
but other times you want to retrieve a previous value and augment it
(as with the previousItems
entry below).
Here's an example:
HttpSession session = request.getSession(true);
session.setAttribute("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getAttribute("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));
// You still have to do setAttribute, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.setAttribute("previousItems", previousItems);
import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.util.Date; public class SessionServlet extends HttpServlet implements Servlet { public SessionServlet() {} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Demo"; String heading; Integer accessCount = new Integer(0);; if (session.isNew()) { heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; Integer oldAccessCount = (Integer)session.getAttribute("accessCount"); if (oldAccessCount != null) { accessCount = new Integer(oldAccessCount.intValue() + 1); } } session.setAttribute("accessCount", accessCount); out.println("<HTML><HEAD><TITLE>"+title+"</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }After building and deploying the downloaded sample code, if you visit http://localhost:1448/SessionDemo/session several times without quiiting your browser in between, you will see a page like this