How to Create a New Session in Java
HttpSession Tutorial
1. What is Session Tracking?
There are a number of problems that arise from the fact that HTTP is a "stateless" protocol because even if a user sends a sequence of requests from the same browser, the server is not able to tell that those are from the same user. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what you have added earlier? When you move from the page where you specify what you want to buy to the page that takes your credit card number and shipping address, how does the server know what is in your cart? 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.
2. The Session Tracking API
Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions.2.1 Looking up the HttpSession object associated with the current request.
This is done by calling thegetSession
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);
2.2 Looking up Information Associated with a Session.
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.
- getId. This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions.
- isNew. This returns
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 returnsfalse
for preexisting sessions. - getCreationTime. This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the
Date
constructor or thesetTimeInMillis
method ofGregorianCalendar
. - getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which the session was last sent from the client.
- getMaxInactiveInterval. This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout.
2.3 Associating Information with a Session
As discussed in the previous section, you read information associated with a session by usinggetAttribute
. 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);
3. Example: Showing Session Information
Here is a simple example that generates a Web page showing some information about the current session. The file session.zip contains the sample code that you can deploy and test on the Tomcat server on our VM.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
This page is modified from: http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Session-Tracking.html
How to Create a New Session in Java
Source: http://web.cs.ucla.edu/classes/winter15/cs144/projects/java/session/
0 Response to "How to Create a New Session in Java"
Post a Comment