10.1 session status overview
The Stateless feature of HTTP brings about a series of problems. Especially when shopping through online stores, the server cannot remember the previous transactions smoothly, which becomes a serious problem. It makes it difficult to implement applications such as "shopping baskets": When we add products to the shopping basket, how can the server know what was originally in the basket? Even if the server saves the context information, we still encounter problems in e-commerce applications. For example, when a user switches from the page of the selected product (provided by a common server) to the page that enters the credit card number and delivery address (provided by a secure server that supports SSL ), how can a server remember what a user has bought?
There are three solutions to this problem:
Cookie. HTTP cookies are used to store information about a shopping session. Subsequent connections can view the current session and extract complete information about the session from some places on the server. This is an excellent and widely used method. However, even if the Servlet provides an advanced and easy-to-use Cookie interface, there are still some complicated details that need to be addressed:
The Cookie that saves the session ID is generated from other cookies.
Set an appropriate expiration time for the Cookie (for example, the session with an interruption duration of more than 24 hours should be reset ).
Associate the session ID with the corresponding information on the server. (The actual information stored may be much more than the information stored in cookies, and sensitive information such as credit card numbers should never be saved using cookies .)
Rewrite the URL. You can append data that identifies a session to the end of each URL. The server can associate the session ID with the session data it stores. This is also a good method, and is also effective when the browser does not support cookies or the user has disabled cookies. However, most of the problems encountered when using cookies are the same, that is, the server-side programs need to perform a lot of simple but monotonous and lengthy processing. In addition, you must be very careful to ensure that the necessary information (including non-direct, such as the Redirection URL given by Location) is appended to each URL ). If the user returns a message through bookmarks after the session ends, the session information will be lost.
Hide form fields. The HTML form can contain the following INPUT fields: <input type = "HIDDEN" NAME = "session" VALUE = "...">. This means that when the form is submitted, the name and data of the hidden field are also included in the GET or POST data. We can use this mechanism to maintain session information. However, this method has a major drawback. It requires that all pages be dynamically generated, because the core of the entire problem is that each session must have a unique identifier.
Servlet provides us with a different solution: HttpSession API. HttpSession API is an advanced session status tracking Interface Based on Cookie or URL rewriting mechanism: If the browser supports cookies, use cookies. If the browser does not support cookies or the Cookie function is disabled, the URL rewrite method is automatically used. Servlet developers do not need to care about the details or directly process cookies or the information appended to the URL. The API automatically provides Servlet developers with a place to conveniently store session information.
10.2 session status tracking API
Using session information in Servlet is quite simple. The main operations include viewing session objects associated with the current request and creating new session objects when necessary, view the information related to a session, save the information in the session object, and release the session object when the session is completed or aborted.
10.2.1 view the session object of the current request
View the session object of the current request by calling the getSession method of HttpServletRequest. If the getSession method returns null, you can create a new session object. But more often, we specify parameters to automatically create a session object when there is no ready-made session, that is, to specify the getSession parameter as true. Therefore, the first step to access the current request Session object is usually as follows:
HttpSession session = request. getSession (true );
10.2.2 View session-related information
The HttpSession object is stored on the server and is automatically associated with the request sender through background mechanisms such as cookies or URLs. The Session Object provides a built-in data structure in which any number of key-value pairs can be saved. In Servlet APIs of Version 2.1 or earlier, the getValue ("key") method is used to view previously saved data. GetValue returns the Object, so you must convert it to a more specific data type. If the specified key does not exist in the parameter, getValue returns null.
In API 2.2, we recommend that you use getAttribute instead of getValue. This is not only because the names of getAttribute and setAttribute are more matched (putValue is matched with getValue, rather than setValue ), in addition, because setAttribute allows an affiliated HttpSessionBindingListener to monitor the value, putValue cannot.
However, since only a few commercial Servlet engines Support 2.2 currently, we still use getValue in the following example. This is a typical example. It is assumed that ShoppingCart is a class that stores purchased product information:
HttpSession session = request. getSession (true );
ShoppingCart previusitems =
(ShoppingCart) session. getValue ("previusitems ");
If (previusitems! = Null ){
DoSomethingWith (previusitems );
} Else {
Previusitems = new ShoppingCart (...);
DoSomethingElseWith (previusitems );
}
Most of the time we look for the value associated with it based on a specific name, but we can also call getValueNames to get the names of all the attributes. GetValuesNames returns a String array. GetAttributeNames is recommended for API Version 2.2. This is not only because its name is better, but also because it returns an Enumeration, which is more consistent with other methods (such as getHeaders and getParameterNames of HttpServletRequest.
Although developers are most concerned about data stored in session objects, other information is sometimes useful.
GetID: This method returns the unique identifier of the session. This identifier is used as a key in a key-value pair. For example, when only one value is saved in a session or the previous session information is saved.
IsNew: if the client (browser) is not bound to a session, true is returned. This usually means that the session has just been created, rather than the request from the client. For long-existing sessions, the returned value is false.
GetCreationTime: This method returns the time in milliseconds for session creation, counted from 1970.01.01 (GMT. To obtain the time value used to print the output, you can pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar.
GetLastAccessedTime: This method returns the time in milliseconds for the last request sent by the customer, counted from 1970.01.01 (GMT.
GetMaxInactiveInterval: returns the maximum interval in seconds. If the interval between customer requests does not exceed this value, the Servlet engine will keep the session valid. A negative number indicates that the session will never time out.
10.2.3 save data in the Session Object
As described in the preceding section, the getValue method is used to read information stored in sessions (or, for Servlet specifications of Version 2.2, getAttribute is used ). The putValue (or setAttribute) method is used to save the data, and the key and corresponding value are specified. Note that putValue will replace any existing values. Sometimes this is exactly what we need (referringPage in the following example), but sometimes we need to extract the original value and expand it (previusitems in the following example ). The sample code is as follows:
HttpSession session = request. getSession (true );
Session. putValue ("referringPage", request. getHeader ("Referer "));
ShoppingCart previusitems =
(ShoppingCart) session. getValue ("previusitems ");
If (previusitems = null ){
Previusitems = new ShoppingCart (...);
}
String itemID = request. getParameter ("itemID ");
Previusitems. addEntry (Catalog. getEntry (itemID ));
Session. putValue ("previusitems", previusitems );
10.3 instance: displays session information
The following example generates a Web page that displays information about the current session.
Package hall;
Import java. io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java.net .*;
Import java. util .*;
Public class ShowSession extends HttpServlet {
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 = "Searching the Web ";
String heading;
Integer accessCount = new Integer (0 );;
If (session. isNew ()){
Heading = "Welcome, Newcomer ";
} Else {
Heading = "Welcome Back ";
Integer oldAccessCount =
// Use getAttribute instead of getValue in Servlet API 2.2
(Integer) session. getValue ("accessCount ");
If (oldAccessCount! = Null ){
AccessCount =
New Integer (oldAccessCount. intValue () + 1 );
}
}
// Use putAttribute in Servlet API 2.2
Session. putValue ("accessCount", accessCount );
Out. println (ServletUtilities. headWithTitle (title) +
"<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 );
}
}