Ten, session state

zhaozj2021-02-16  194

10.1 Session Status Overview The "stateless" feature of the HTTP protocol has brought a range of questions. Especially when shopping is online, the server can not successfully remember the previous business has become a serious problem. It makes it difficult for the application of "shopping basket" to achieve: When we add goods to the shopping basket, how can the server know what is the original in the basket? Even if the server saves context information, we still encounter problems in e-commerce applications. For example, when the user goes from the page selected by the product (supplied by ordinary servers), the server can remember what the user has bought? This issue generally has three solutions: cookie. With HTTP cookies to store information about shopping sessions, the subsequent connections can view the current session and extract complete information about the session from some places of the server. This is an excellent, and the most widely used method. However, even if servlet provides a high-level, easy to use the easy cookie interface, there are still some cumbersome details that require processing: Save the session ID from other cookies. Set a suitable invalidation time for cookies (for example, a session that interrupts more than 24 hours should be resended). Associate the session identifier and the information of the server side. (The actual saved information may be far more than the information saved to cookie, and sensitive information such as credit card should never be saved with cookies.) Rewriting the URL. You can attach the data of some identity sessions to each URL, and the server can associate the session identifier and the session data it saved. This is also a good method, and there is also the advantage when the browser does not support cookies or users have disabled cookies. However, most of the problems faced when using cookies also exist, that is, the server-side procedures should make a lot of simple but monotonous lengthy processing. In addition, you must also carefully ensure that the necessary information (including non-direct, such as a redirect URL given by Location) is guaranteed. If the user ends the session, the session information will be lost if the bookmark is returned. Hidden form fields. The HTML form can contain the following input domain:

10.2 Session Status Tracking API Using Session Information in Servlet is quite simple, the main operations include: viewing the session objects associated with the current request, create a new session object when necessary, view information related to a session, in the session Save information in the object, and release the session object when the session is completed or aborted. 10.2.1 Viewing the currently requested session object View the currently requested session object is implemented by calling the GetSession method of httpservletRequest. If the getSession method returns null, you can create a new session object. More often, we automatically create a session object when there are no ready-made sessions, namely TRUE when there is no ready-made session, ie specified GetSession parameters. Therefore, the first step of accessing the current request session object is usually as follows: httpsession session = request.getSession (TRUE); 10.2.2 Viewing the information about the HTTPSession object HttpSession objects There is a servers, through the cookie or URL background The mechanism is automatically associated with the requesting sender. The session object provides a built-in data structure where any number of keys-value pairs can be saved in this structure. In the 2.1 or earlier version of the Servlet API, check the previously saved data is the GetValue ("Key") method. getValue Returns Object, so you have to convert it into a more specific data type. If the keys specified in the parameter do not exist, getValue returns NULL. API version 2.2 is recommended getAttribute instead of getValue, not only because getAttribute and setAttribute name more closely matches (and getValue match is putValue, rather than setValue), but also because setAttribute allows the use of a subsidiary of HttpSessionBindingListener to monitor the value, and putValue Can't. However, because there is only a few commercial servlet engines support 2.2, we still use GetValue in the examples. This is a very typical example, assuming ShoppingCart is a save purchased items of information such as: HttpSession session = request.getSession (true); ShoppingCart previousItems = (ShoppingCart) session.getValue ( "previousItems"); if (previousItems =! NULL) {DOSMETHINGWITH (PREVIOSMS);} else {previousItems = new shoppingcart (...); DOSMETHINGELSEWITH (PREVIOSELSEWITH (PREVIOSEMS); The name of all attributes. GetValueSNames returns a string array. The API 2.2 is recommended to use GetAttributeNames, which is not only because of its name, but because it returns an enumeration, and other methods (such as HTTPSERVLETREQUEST's GetHeaders and getParameternames) are consistent. Although developers are often the data saved to session objects, there are still other information. GetID: This method returns the unique identifier of the session.

Sometimes the identity is used as a key-value pair, such as only one value is saved in the session, or saves the last session information. Isnew: Returns true if the customer (browser) has not bind to a session, often means that the session has just created, not a request from the client. For a session that has already existed, the return value is false. GetCreationTime: This method returns to establish a session time in millisecond meters, from 1970.01.01 (gmt). To get the time value for printout, the value can be passed to the Date constructor, or the settimeinmillis method of GregorianCalendar. GetLastAccesseedTime: This method returns to the customer's last time the request is measured in milliseconds, from 1970.01.01 (gmt). GetMaxInactiveInterval: Returns the maximum time interval in seconds, if the interval between the customer request does not exceed this value, the servlet engine will keep the session is valid. Negative numbers indicate that the session will never time out. 10.2.3 Save Data in the Session Object As described above, read the information stored in the session uses the getValue method (or, for the 2.2 version of the servlet specification, use GetAttribute). Save Data Use the PUTVALUE (or SetAttribute) method and specify the key and the corresponding value. Note 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 (as PreviousItems). The following sample code: 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 Example: Display Session Information Below this example generates a web page and displays information about the current session in this 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 = // In Servlet API 2.2 getAttribute used instead getValue (Integer) session.getValue ( "accessCount"); if (oldAccessCount = null!) {accessCount = new Integer (oldAccessCount.intValue () 1);}} // 2.2 Servlet API used in putAttribute Session.putValue ("AccessCount", AccessCount; Out.pri NTLN (servletutilities.headwithtitle (title) \N " "

heading " \N" "

Information on your session: \N " " \N " " \N" "

转载请注明原文地址:https://www.9cbs.com/read-8978.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.041, SQL: 9