Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

Accessing Databases from Web Applications

Data that is shared between Web components and persistent between invocations of a Web application is usually maintained in a database. Web applications use the JDBC 2.0 API to access relational databases. For information on this API, see

http://java.sun.com/docs/books/tutorial/jdbc 

In the JDBC API, databases are accessed via DataSource objects. A DataSource has a set of properties that identify and describe the real world data source that it represents. These properties include information like the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on.

Applications access a data source using a connection, and a DataSource object can be thought of as a factory for connections to the particular data source that the DataSource instance represents. In a basic DataSource implementation, a call to the method DataSource.getConnection returns a connection object that is a physical connection to the data source.

If a DataSource object is registered with a JNDI naming service, an application can use the JNDI API to access that DataSource object, which can then be used to connect to the data source it represents.

DataSource objects that implement connection pooling also produce a connection to the particular data source that the DataSource class represents. The connection object that the method DataSource.getConnection returns is a handle to a PooledConnection object rather than being a physical connection. An application uses the connection object like any other connection. Connection pooling has no effect on application code except that a pooled connection, like all connections, should always be explicitly closed. When an application closes a connection that is pooled, the connection is returned to a pool of reusable connections. The next time DataSource.getConnection is called, a handle to one of these pooled connections will be returned if one is available. Because connection pooling avoids creating a new physical connection every time one is requested, it can help applications run significantly faster.

The Duke's Bookstore examples use the PointBase evaluation database to maintain the catalog of books. This section describes how to:

Installing and Starting the PointBase Database Server

You can download an evaluation copy of the PointBase 4.6 database from:

http://www.pointbase.com 

Make sure to choose a platform-specific (UNIX or Windows) installation package. Install the client and server components. After you have downloaded and installed the PointBase database, do the following:

  1. Add a pb.home property to your build.properties file (discussed in Managing the Examples) that points to your PointBase install directory. On Windows the syntax of the entry must be
  2.   pb.home=drive:\\<PB_HOME> 
    
  3. Copy <PB_HOME>/lib/pbclient46.jar to <JWSDP_HOME>/common/lib to make the PointBase client library available to the example applications. If Tomcat is running, restart it so that it loads the client library.

To start the PointBase database server:

  1. In a terminal window, go to <PB_HOME>/tools/serveroption.
  2. Execute the startserver script.

Populating the Example Database

To populate the database for the Duke's Bookstore examples:

  1. In a terminal window, go to <INSTALL>/jwstutorial12/examples/web/bookstore.
  2. Run ant create-pointbase-db. This task runs a PointBase commander tool command to read the file books.sql and execute the SQL commands contained in the file. The table named books is created for the user pbpublic in the sample PointBase database.
  3. At the end of the processing, you should see the following output:
  4. ...
    [java] SQL> INSERT INTO books VALUES('207', 'Thrilled', 'Ben',
    [java]  'The Green Project: Programming for Consumer Devices',
    [java]  30.00, false, 1998, 'What a cool book', 20);
    [java] 1 row(s) affected
    
    [java] SQL> INSERT INTO books VALUES('208', 'Tru', 'Itzal',
    [java]  'Duke: A Biography of the Java Evangelist',
    [java]  45.00, true, 2001, 'What a cool book.', 20);
    [java] 1 row(s) affected 
    

You can check that the table exists with the PointBase console tool as follows:

  1. In a terminal window, go to <PB_HOME>/tools/serveroption/.
  2. Execute startconsole.
  3. In the Connect to Database dialog
    1. Enter jdbc:pointbase:server://localhost/sample in the URL field.
    2. Enter PBPUBLIC in the password field.
  4. Click OK.
  5. Expand the SCHEMASRight ArrowPBPUBLICRight ArrowTABLES nodes. Notice that there is a table named BOOKS.
  6. To see the contents of the books table:
    1. In the Enter SQL commands text area, enter select * from books;.
    2. Click the Execute button.

Defining a Data Source in Tomcat

In order to use a database you must create a data source in Tomcat. The data source contains information about the driver class and URL used to connect to the database and database login parameters. To define a data source in Tomcat, you use admintool (see Configuring Data Sources) as follows:

  1. Start admintool by opening a browser at:
  2.   http://localhost:8080/admin/index.jsp 
    
  3. Log in using the user name and password you specified when you installed the Java WSDP.
  4. Select the Data Sources entry under Resources.
  5. Select Available ActionsRight ArrowCreate New Data Source.
  6. Enter pointbase in the JNDI Name field.
  7. Enter jdbc:pointbase:server://localhost/sample in the Data Source URL field.
  8. Enter com.pointbase.jdbc.jdbcUniversalDriver in the JDBC Driver Class field.
  9. Enter public in the User Name and Password fields.
  10. Click the Save button.
  11. Click the Commit button.

Configuring the Web Application to Reference a Data Source with JNDI

In order to access a database from a Web application, you must declare resource reference in the application's Web application deployment descriptor (see Declaring References to Environment Entries, Resource Environment Entries, or Resources). The resource reference declares a JNDI name, the type of the data resource, and the kind of authentication used when the resource is accessed. The JNDI name is used to create a data source object in the database helper class database.BookDB:

public BookDB () throws Exception {
  try  { 
    Context initCtx = new InitialContext();
    Context envCtx = (Context)
      initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup("jdbc/BookDB");
    con =  ds.getConnection();
    System.out.println("Created connection to database.");
  } catch (Exception ex) {
    System.out.println("Couldn't create connection." + 
    ex.getMessage());
    throw new 
      Exception("Couldn't open connection to database: "
    +ex.getMessage());
  }  

To specify a resource reference to the bookstore data source, the bookstore deployment descriptors include the following element:

<resource-ref>
  <res-ref-name>jdbc/BookDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref> 

The JNDI name is used to create a data source object in the database helper class database.BookDB used by the tutorial examples. The res-auth element specifies that the container will manage logging on to the database.

Mapping the Web Application JNDI Name to a Data Source

Since the resource reference declared in the Web application deployment descriptor uses a JNDI name to refer to the data source, you must connect the name to a data source by providing a resource link entry in Tomcat's configuration. Here is the entry used by the application discussed in all the Web technology chapters:

<Context path="/bookstore1"
  docBase="../../jwstutorial12/examples/web/bookstore1/build" 
  debug="0">
  <ResourceLink name="jdbc/BookDB" global="pointbase"/>
</Context> 

Since the resource link is a subentry of the context entry described in Installing Web Applications and Deploying Web Applications, you add this entry to Tomcat's configuration in the same ways that you add the context entry: by passing the name of a configuration file containing the entry to the config attribute of the Ant install-config task or by copying the configuration file named mywebapp.xml that contains the context entry to <JWSDP_HOME>/webapps.

If you are deploying the application using the Ant deploy task, you must package a configuration file named context.xml containing the context entry in the META-INF directory of the WAR.

The examples discussed in chapters 15, 16, 17, and 18 show how to install applications using the Ant install-config task mechanism.

Divider
Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

All of the material in The Java(TM) Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.