Sharing Information



Sharing Information

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 Invoking Other Web Resources (page 389).

1 Using Scope Objects

Collaborating Web components share information via objects maintained as attributes of four scope objects. These attributes are accessed with the [get|set]Attribute methods of the class representing the scope. Figure lists the scope objects.

Scope Objects

Scope Object

Class

Accessible From

Web context

javax.servlet.ServletContext

Web components within a Web context. See Accessing the Web Context (page 392).

session

javax.servlet.http.HttpSession

Web components handling a request that belongs to the session. See Maintaining Client State (page 393).

request

subtype of javax.servlet.ServletRequest

Web components handling the request.

page

javax.servlet.jsp.PageContext

The JSP page that creates the object. See Implicit Objects (page 410).

Figure shows the scoped attributes maintained by the Duke's Bookstore application.

1. Duke's Bookstore Scoped Attributes
graphics/13fig01.gif

2 Controlling Concurrent Access to Shared Resources

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:

  • Multiple Web components accessing objects stored in the Web context.

  • Multiple Web components accessing objects stored in a session.

  • 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 SingleThreadModel 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.

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 Threads Lesson in the Java Tutorial.

In the previous section we showed five scoped attributes shared by more than one servlet: bookDB, cart, currency, hitCounter, and orderCounter. The bookDB 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 util.Counter class:


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); 
    } 
}

3 Accessing Databases

Data that is shared between Web components and 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 database.BookDB. For example, ReceiptServlet invokes the BookDB.buyBooksmethod to update the book inventory when a user makes a purchase. The buyBooks method invokes buyBook for each book contained in the shopping cart. To ensure the order is processed in its entirety, the calls to buyBook are wrapped in a single JDBC transaction. The use of the shared database connection is synchronized via the [get|release]Connection methods.


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()); 
        } 
    } 
}