Ten, Session state

Source: Internet
Author: User
Tags date object html form http cookie integer string version time interval
10.1 Session State Overview

The "Stateless" (stateless) characteristics of the HTTP protocol bring a series of problems. In particular, when shopping through an online store, it is a serious problem for the server not to remember the previous transaction smoothly. It makes it hard to make apps like "shopping baskets": How does the server know what's in the basket when we add it to the shopping basket? Even if the server holds contextual information, we still have problems with e-commerce applications. For example, when a user transfers from a page that selects a product (provided by a regular server) to a page that enters a credit card number and delivery address (provided by a secure server that supports SSL), how can the server remember what the user has bought?

There are generally three solutions to this problem:

Cookies. Using an HTTP cookie to store information about a shopping session, subsequent connections can view the current session and then extract complete information about the session from somewhere on the server. This is an excellent and widely used method. However, even if the servlet provides an advanced, Easy-to-use cookie interface, there are still some tedious details to deal with:
Separate cookies from the other cookies that hold the session identity.
Set the appropriate time out for cookies (for example, sessions that break for more than 24 hours should generally be reset).
Associate the session identifier with the corresponding information on the server side. (The actual information saved may be much more than the information saved to the cookie, and sensitive information such as credit card numbers should never be saved with cookies.) )
Overwrite the URL. You can attach some data that identifies the session to the back of each URL, and the server can associate the session identity with the session data it holds. This is also a good way to do this, and it is also useful when the browser does not support cookies or if the user has disabled cookies. However, the problem with most cookies is that the server-side programs do a lot of simple but tedious processing. In addition, you must be very careful to ensure that the necessary information is appended to each URL (including indirect, such as a redirected URL given through location). If the user ends the session and then returns through the bookmark, the session information is lost.
Hides form fields. An HTML form can contain input fields such as the following: <input type= "HIDDEN" name= "session" Value= "...". This means that when a form is submitted, the name and data of the hidden field are also included in the Get or post data, and we can use this mechanism to maintain session information. However, there is a big drawback to this approach, which requires that all pages are dynamically generated, because the core of the whole problem is that each session must have a unique identifier.
The servlet provides us with a different scenario: the HttpSession API. The HttpSession API is an advanced session state tracking interface based on a cookie or URL rewriting mechanism: If the browser supports cookies, use cookies, and if the browser does not support cookies or if the cookie feature is turned off, the URL rewriting method is automatically used. The servlet developer does not need to care about the details, nor does it have to deal directly with cookies or the information appended to the URL, which automatically provides the servlet developer with an easy place to store session information.

   10.2 Session state Tracking API

Session information is fairly straightforward to use in the servlet, and the main actions include viewing the session object associated with the current request, creating a new Session object when necessary, viewing information related to a session, saving information in the session object, and releasing the session object when the session completes or aborts.

10.2.1 View the Session object for the current request

The session object that views the current request is implemented by calling the HttpServletRequest GetSession method. If the GetSession method returns NULL, you can create a new session object. More often, however, we create a session object automatically by specifying the parameters so that no ready-made session exists, specifying that the GetSession argument is true. Therefore, the first step in accessing the current request session object is usually as follows:
HttpSession session = Request.getsession (true);

10.2.2 View and session-related information

The HttpSession object survives on the server and is automatically associated with the sender of the request through a background mechanism such as a cookie or URL. The Session object provides a built-in data structure in which any number of key-value pairs can be saved. In 2.1 or earlier servlet APIs, the GetValue ("key") method was used to view previously saved data. GetValue returns object, so you have to convert it to a more specific data type. If the key specified in the parameter does not exist, GetValue returns NULL.

API version 2.2 recommends replacing GetValue with getattribute, not only because GetAttribute and setattribute names are more matched (GetValue matches putvalue rather than SetValue). Also because SetAttribute allows an attached httpsessionbindinglistener to be used to monitor values, Putvalue does not.

However, as there are currently only a few commercial servlet engines supporting 2.2, we still use GetValue in the example below. This is a typical example of the assumption that ShoppingCart is a class that holds information about purchased goods:

HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}

Most of the time we look for the value associated with it based on a particular name, but we can also call GetValueNames to get the names of all the attributes. Getvaluesnames returns an array of strings. API version 2.2 recommends using Getattributenames, not only because its name is better, but because it returns a enumeration, More consistent with other methods, such as HttpServletRequest's Getheaders and Getparameternames.

While developers are most concerned with storing data for session objects, other information is sometimes useful.

GetID: This method returns the unique identity of the session. Sometimes the identity is used as a key in a key-value pair, such as when only one value is saved in a session, or when the last session information is saved.
IsNew: Returns True if the client (browser) is not bound to the session, which usually means that the conversation was just created, not a request from the client. For a session that already exists, the return value is false.
GetCreationTime: This method returns the millisecond time of establishing the session, calculated from 1970.01.01 (GMT). To get the time value for the printout, you can pass the value to the date constructor, or the GregorianCalendar Settimeinmillis method.
Getlastaccessedtime: This method returns the millisecond time, calculated from 1970.01.01 (GMT), that the customer last sent the request.
Getmaxinactiveinterval: Returns the maximum time interval in seconds, and if the interval between customer requests does not exceed that value, the servlet engine will maintain session validity. A negative number indicates that the session never times out.
10.2.3 save data in a Session object

As described in the previous section, reading information saved in a session uses the GetValue method (or, for the 2.2 servlet specification, use getattribute). Save the data using the Putvalue (or setattribute) method and specify the key and corresponding value. Note that Putvalue will replace any existing values. Sometimes this is exactly what we need (referringpage in the example below), but sometimes we need to extract the original value and expand it (the following example Previousitems). The sample code is as follows:

HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));

session.putValue("previousItems", previousItems);


   10.3 instance: displaying session information

The following example generates a Web page and displays information about the current session on the page.

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 =
Using getattribute instead of GetValue in servlet API 2.2
(Integer) Session.getvalue ("Accesscount");
if (Oldaccesscount!= null) {
Accesscount =
New Integer (Oldaccesscount.intvalue () + 1);
}
}
Using Putattribute in servlet API 2.2
Session.putvalue ("Accesscount", Accesscount);

Out.println (title) + Servletutilities.headwithtitle
"<body bgcolor=\" #FDF5E6 \ ">\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);
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.