📄 servlets11.html
字号:
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Maintaining Client State</title> <link rel="StyleSheet" href="document.css" type="text/css" media="all" /> <link rel="StyleSheet" href="catalog.css" type="text/css" media="all" /> <link rel="Table of Contents" href="J2EETutorialTOC.html" /> <link rel="Previous" href="Servlets10.html" /> <link rel="Next" href="Servlets12.html" /> <link rel="Index" href="J2EETutorialIX.html" /> </head> <body> <table width="550" summary="layout" id="SummaryNotReq1"> <tr> <td align="left" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a> </td> <td align="center" valign="center"><a accesskey="p" href="Servlets10.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="Servlets12.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a> </td> <td align="right" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font> </font> </td> </tr> </table> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"> <blockquote><a name="wp64744"> </a><h2 class="pHeading1">Maintaining Client State</h2><a name="wp64745"> </a><p class="pBody">Many applications require a series of requests from a client to be associated with one another. For example, the Duke's Bookstore application saves the state of a user's shopping cart across requests. Web-based applications are responsible for maintaining such state, called a <em class="cEmphasis">session</em>, because the HTTP protocol is stateless. To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.</p><a name="wp64748"> </a><h3 class="pHeading2">Accessing a Session</h3><a name="wp64751"> </a><p class="pBody">Sessions are represented by an <code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html" target="_blank">HttpSession</a></code> object. You access a session by calling the <code class="cCode">getSession</code> method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one.</p><a name="wp64754"> </a><h3 class="pHeading2">Associating Attributes with a Session</h3><a name="wp64756"> </a><p class="pBody">You can associate object-valued attributes with a session by name. Such attributes are accessible by any Web component that belongs to the same Web context <em class="cEmphasis">and</em> is handling a request that is part of the same session.</p><a name="wp64757"> </a><p class="pBody">The Duke's Bookstore application stores a customer's shopping cart as a session attribute. This allows the shopping cart to be saved between requests and also allows cooperating servlets to access the cart. <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/CatalogServlet.java" target="_blank">CatalogServlet</a></code> adds items to the cart; <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/ShowCartServlet.java" target="_blank">ShowCartServlet</a></code> displays, deletes items from, and clears the cart; and <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/CashierServlet.java" target="_blank">CashierServlet</a></code> retrieves the total cost of the books in the cart.</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session. getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();<a name="wp64761"> </a></pre></div><a name="wp64762"> </a><h4 class="pHeading3">Notifying Objects That Are Associated with a Session</h4><a name="wp64763"> </a><p class="pBody">Recall that your application can notify Web context and session listener objects of servlet life cycle events (<a href="Servlets4.html#wp64218">Handling Servlet Life Cycle Events</a>). You can also notify objects of certain events related to their association with a session such as the following:</p><div class="pSmartList1"><ul class="pSmartList1"><a name="wp64768"> </a><div class="pSmartList1"><li>When the object is added to or removed from a session. To receive this notification, your object must implement the <code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionBindingListener.html" target="_blank">javax.http.HttpSessionBindingListener</a></code> interface<code class="cCode">.</code></li></div><a name="wp64770"> </a><div class="pSmartList1"><li>When the session to which the object is attached will be passivated or activated. A session will be passivated or activated when it is moved between virtual machines or saved to and restored from persistent storage. To receive this notification, your object must implement the <code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionActivationListener.html" target="_blank">javax.http.HttpSessionActivationListener</a></code> interface.</li></div></ul></div><a name="wp64772"> </a><h3 class="pHeading2">Session Management</h3><a name="wp81561"> </a><p class="pBody">Since there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed with a session's <code class="cCode">[get|set]MaxInactiveInterval</code> methods. You can also set the time-out period with <code class="cCode">deploytool</code>:</p><div class="pSmartList1"><ol type="1" class="pSmartList1"><a name="wp81562"> </a><div class="pSmartList1"><li>Select the WAR.</li></div><a name="wp81563"> </a><div class="pSmartList1"><li>Select the General tab.</li></div><a name="wp81564"> </a><div class="pSmartList1"><li>Click the Advanced Setting button.</li></div><a name="wp81565"> </a><div class="pSmartList1"><li>Enter the time-out period in the Session timeout field.</li></div></ol></div><a name="wp64777"> </a><p class="pBody">To ensure that an active session is not timed out, you should periodically access the session via service methods because this resets the session's time-to-live counter.</p><a name="wp64779"> </a><p class="pBody">When a particular client interaction is finished, you use the session's <code class="cCode">invalidate</code> method to invalidate a session on the server side and remove any session data.</p><a name="wp64782"> </a><p class="pBody">The bookstore application's <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/ReceiptServlet.java" target="_blank">ReceiptServlet</a></code> is the last servlet to access a client's session, so it has responsibility for invalidating the session:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); // Payment received -- invalidate the session session.invalidate(); ...<a name="wp64783"> </a></pre></div><a name="wp64784"> </a><h3 class="pHeading2">Session Tracking</h3><a name="wp68237"> </a><p class="pBody">A Web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and server. The identifier can be maintained on the client as a cookie or the Web component can include the identifier in every URL that is returned to the client.</p><a name="wp64786"> </a><p class="pBody">If your application makes use of session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response's <code class="cCode">encodeURL(URL)</code> method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged. </p><a name="wp64791"> </a><p class="pBody">The <code class="cCode">doGet</code> method of <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/ShowCartServlet.java" target="_blank">ShowCartServlet</a></code> encodes the three URLs at the bottom of the shopping cart display page as follows:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">out.println("<p> &nbsp; <p><strong><a href=\"" + response.encodeURL(request.getContextPath() + "/bookcatalog") + "\">" + messages.getString("ContinueShopping") + "</a> &nbsp; &nbsp; &nbsp;" + "<a href=\"" + response.encodeURL(request.getContextPath() + "/bookcashier") + "\">" + messages.getString("Checkout") + "</a> &nbsp; &nbsp; &nbsp;" + "<a href=\"" + response.encodeURL(request.getContextPath() + "/bookshowcart?Clear=clear") + "\">" + messages.getString("ClearCart") + "</a></strong>");<a name="wp64792"> </a></pre></div><a name="wp64793"> </a><p class="pBody">If cookies are turned off, the session is encoded in the Check Out URL as follows:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">http://localhost:<code class="cCode">8080</code>/bookstore1/cashier; jsessionid=c0o7fszeb1<a name="wp64794"> </a></pre></div><a name="wp64795"> </a><p class="pBody">If cookies are turned on, the URL is simply</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">http://localhost:<code class="cCode">8080</code>/bookstore1/cashier<a name="wp64796"> </a></pre></div> </blockquote> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"> <table width="550" summary="layout" id="SummaryNotReq1"> <tr> <td align="left" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/download.html#tutorial" target="_blank">Download</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/faq.html" target="_blank">FAQ</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/history.html" target="_blank">History</a> </td> <td align="center" valign="center"><a accesskey="p" href="Servlets10.html"><img id="LongDescNotReq1" src="images/PrevArrow.gif" width="26" height="26" border="0" alt="Prev" /></a><a accesskey="c" href="J2EETutorialFront.html"><img id="LongDescNotReq1" src="images/UpArrow.gif" width="26" height="26" border="0" alt="Home" /></a><a accesskey="n" href="Servlets12.html"><img id="LongDescNotReq3" src="images/NextArrow.gif" width="26" height="26" border="0" alt="Next" /></a><a accesskey="i" href="J2EETutorialIX.html"></a> </td> <td align="right" valign="center"> <font size="-1"> <a href="http://java.sun.com/j2ee/1.4/docs/api/index.html" target="_blank">API</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/search.html" target="_blank">Search</a> <br> <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/information/sendusmail.html" target="_blank">Feedback</a></font> </font> </td> </tr> </table> <img src="images/blueline.gif" width="550" height="8" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT="Divider"><p><font size="-1">All of the material in <em>The J2EE(TM) 1.4 Tutorial</em> is <a href="J2EETutorialFront2.html">copyright</a>-protected and may not be published in other workswithout express written permission from Sun Microsystems.</font> </body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -