Download
FAQ History |
![]() ![]() ![]() |
API
Search Feedback |
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
In the JDBC API, databases are accessed via
DataSource
objects. ADataSource
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 theDataSource
instance represents. In a basicDataSource
implementation, a call to the methodDataSource.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 thatDataSource
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 theDataSource
class represents. The connection object that the methodDataSource.getConnection
returns is a handle to aPooledConnection
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 timeDataSource.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:
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:
- Add a
pb.home
property to yourbuild.properties
file (discussed in Managing the Examples) that points to your PointBase install directory. On Windows the syntax of the entry must be- 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:
Populating the Example Database
To populate the database for the Duke's Bookstore examples:
- In a terminal window, go to
<
INSTALL
>/jwstutorial12/examples/web/bookstore
.- Run
ant
create-pointbase-db
. This task runs a PointBase commander tool command to read the filebooks.sql
and execute the SQL commands contained in the file. The table namedbooks
is created for the userpbpublic
in thesample
PointBase database.- At the end of the processing, you should see the following output:
... [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) affectedYou can check that the table exists with the PointBase console tool as follows:
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
(seeConfiguring Data Sources
)
as follows:
- Start
admintool
by opening a browser at:- Log in using the user name and password you specified when you installed the Java WSDP.
- Select the Data Sources entry under Resources.
- Select Available Actions
Create New Data Source.
- Enter
pointbase
in the JNDI Name field.- Enter
jdbc:pointbase:server://localhost/sample
in the Data Source URL field.- Enter
com.pointbase.jdbc.jdbcUniversalDriver
in the JDBC Driver Class field.- Enter
public
in the User Name and Password fields.- Click the Save button.
- 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. Theres-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 theAnt
install-config
task or by copying the configuration file namedmywebapp
.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 namedcontext.xml
containing the context entry in theMETA-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.
Download
FAQ History |
![]() ![]() ![]() |
API
Search Feedback |
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.