📄 servlets5.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>Sharing Information</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="Servlets4.html" /> <link rel="Next" href="Servlets6.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="Servlets4.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="Servlets6.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="wp66698"> </a><h2 class="pHeading1">Sharing Information</h2><a name="wp64310"> </a><p class="pBody">Web components, like most objects, usually work with other objects to accomplish their tasks. There are several ways they can do this. They can use private helper objects (for example, JavaBeans components), they can share objects that are attributes of a public scope, they can use a database, and they can invoke other Web resources. The Java Servlet technology mechanisms that allow a Web component to invoke other Web resources are described in <a href="Servlets9.html#wp64684">Invoking Other Web Resources</a>.</p><a name="wp64315"> </a><h3 class="pHeading2">Using Scope Objects</h3><a name="wp64316"> </a><p class="pBody">Collaborating Web components share information via objects maintained as attributes of four scope objects. These attributes are accessed with the <code class="cCode">[get|set]Attribute</code> methods of the class representing the scope. <a href="Servlets5.html#wp64327">Table 11-4</a> lists the scope objects.</p><div align="left"><table border="1" summary="Scope Objects" id="wp64327"> <caption><a name="wp64327"> </a><div class="pTableTitle">Table 11-4 Scope Objects </div></caption> <tr align="center"> <th><a name="wp64333"> </a><div class="pCellHeading">Scope Object</div></th> <th><a name="wp64335"> </a><div class="pCellHeading">Class</div></th> <th><a name="wp64337"> </a><div class="pCellHeading">Accessible From</div></th></tr> <tr align="left"> <td><a name="wp64339"> </a><div class="pCellBody">Web context</div></td> <td><a name="wp64342"> </a><div class="pCellBody"><code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html" target="_blank">javax.servlet.<br />ServletContext</a></code></div></td> <td><a name="wp64344"> </a><div class="pCellBody">Web components within a Web context. See <a href="Servlets10.html#wp64724"><span style="text-decoration: none">Accessing the Web Context </span></a><span style="text-decoration: underline">.</span></div></td></tr> <tr align="left"> <td><a name="wp64349"> </a><div class="pCellBody">session</div></td> <td><a name="wp64352"> </a><div class="pCellBody"><code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html" target="_blank">javax.servlet.<br />http.HttpSession</a></code></div></td> <td><a name="wp64354"> </a><div class="pCellBody">Web components handling a request that belongs to the session. See <a href="Servlets11.html#wp64744">Maintaining Client State </a>.</div></td></tr> <tr align="left"> <td><a name="wp64359"> </a><div class="pCellBody">request</div></td> <td><a name="wp64361"> </a><div class="pCellBody">subtype of <br /><code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletRequest.html" target="_blank">javax.servlet.<br />ServletRequest</a></code></div></td> <td><a name="wp64364"> </a><div class="pCellBody">Web components handling the request.</div></td></tr> <tr align="left"> <td><a name="wp64366"> </a><div class="pCellBody">page</div></td> <td><a name="wp64369"> </a><div class="pCellBody"><code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/JspContext.html" target="_blank">javax.servlet.<br />jsp.JspContext</a></code></div></td> <td><a name="wp64371"> </a><div class="pCellBody">The JSP page that creates the object. See <a href="JSPIntro6.html#wp66045"><span style="text-decoration: none">Implicit Objects </span></a><span style="text-decoration: underline">.</span></div></td></tr></table></div><p class="pBody"></p><a name="wp64378"> </a><p class="pBody"><a href="Servlets5.html#wp64384">Figure 11-1</a> shows the scoped attributes maintained by the Duke's Bookstore application.</p><a name="wp64382"> </a><p class="pBody"></p><div align="center"><img src="images/Fig23.gif" height="246" width="446" alt="Duke's Bookstore Scoped Attributes" border="0" hspace="0" vspace="0"/></div><p class="pBody"></p><p> <a name="64384"> </a><strong><font >Figure 11-1 Duke's Bookstore Scoped Attributes</font></strong></p><a name="wp64386"> </a><h3 class="pHeading2">Controlling Concurrent Access to Shared Resources</h3><a name="wp64388"> </a><p class="pBody">In a multithreaded server, it is possible for shared resources to be accessed concurrently. Besides scope object attributes, shared resources include in-memory data such as instance or class variables, and external objects such as files, database connections, and network connections. Concurrent access can arise in several situations:</p><div class="pSmartList1"><ul class="pSmartList1"><a name="wp64389"> </a><div class="pSmartList1"><li>Multiple Web components accessing objects stored in the Web context</li></div><a name="wp64390"> </a><div class="pSmartList1"><li>Multiple Web components accessing objects stored in a session</li></div><a name="wp75172"> </a><div class="pSmartList1"><li>Multiple threads within a Web component accessing instance variables. A Web container will typically create a thread to handle each request. If you want to ensure that a servlet instance handles only one request at a time, a servlet can implement the <code class="cCode"><a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/SingleThreadModel.html" target="_blank">SingleThreadModel</a></code> interface. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. A Web container can implement this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of Web component instances and dispatching each new request to a free instance. This interface does not prevent synchronization problems that result from Web components accessing shared resources such as static class variables or external objects. In addition, the Servlet 2.4 specification deprecates <code class="cCode">SingleThreadModel</code>.</li></div></ul></div><a name="wp75176"> </a><p class="pBody">When resources can be accessed concurrently, they can be used in an inconsistent fashion. To prevent this, you must control the access using the synchronization techniques described in the <a href="http://java.sun.com/docs/books/tutorial/essential/threads/index.html" target="_blank">Threads</a> lesson in <em class="cEmphasis"><a href="http://java.sun.com/docs/books/tutorial" target="_blank">The Java Tutorial</a></em>.</p><a name="wp64397"> </a><p class="pBody">In the previous section we showed five scoped attributes shared by more than one servlet: <code class="cCode">bookDB</code>, <code class="cCode">cart</code>, <code class="cCode">currency</code>, <code class="cCode">hitCounter</code>, and <code class="cCode">orderCounter</code>. The <code class="cCode">bookDB</code> attribute is discussed in the next section. The cart, currency, and counters can be set and read by multiple multithreaded servlets. To prevent these objects from being used inconsistently, access is controlled by synchronized methods. For example, here is the <code class="cCode"><a href="../examples/web/bookstore1/src/util/Counter.java" target="_blank">util.Counter</a></code> class:</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public class Counter { private int counter; public Counter() { counter = 0; } public synchronized int getCounter() { return counter; } public synchronized int setCounter(int c) { counter = c; return counter; } public synchronized int incCounter() { return(++counter); }}<a name="wp64399"> </a></pre></div><a name="wp64401"> </a><h3 class="pHeading2">Accessing Databases</h3><a name="wp64402"> </a><p class="pBody">Data that is shared between Web components and is persistent between invocations of a Web application is usually maintained by a database. Web components use the JDBC 2.0 API to access relational databases. The data for the bookstore application is maintained in a database and accessed through the helper class <code class="cCode"><a href="../examples/web/bookstore1/src/database/BookDB.java" target="_blank">database.BookDB</a></code>. For example, <code class="cCode"><a href="../examples/web/bookstore1/src/servlets/ReceiptServlet.java" target="_blank">ReceiptServlet</a></code> invokes the <code class="cCode">BookDB.buyBooks</code> method to update the book inventory when a user makes a purchase. The <code class="cCode">buyBooks</code> method invokes <code class="cCode">buyBook</code> for each book contained in the shopping cart. To ensure the order is processed in its entirety, the calls to <code class="cCode">buyBook</code> are wrapped in a single JDBC transaction. The use of the shared database connection is synchronized via the <code class="cCode">[get|release]Connection</code> methods.</p><div class="pPreformattedRelative"><pre class="pPreformattedRelative">public void buyBooks(ShoppingCart cart) throws OrderException { Collection items = cart.getItems(); Iterator i = items.iterator(); try { getConnection(); con.setAutoCommit(false); while (i.hasNext()) { ShoppingCartItem sci = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)sci.getItem(); String id = bd.getBookId(); int quantity = sci.getQuantity(); buyBook(id, quantity); } con.commit(); con.setAutoCommit(true); releaseConnection(); } catch (Exception ex) { try { con.rollback(); releaseConnection(); throw new OrderException("Transaction failed: " + ex.getMessage()); } catch (SQLException sqx) { releaseConnection(); throw new OrderException("Rollback failed: " + sqx.getMessage()); } } }<a name="wp68020"> </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="Servlets4.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="Servlets6.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 + -