Introduction

Tomcat provides a JNDI InitialContext implementation
instance for each web application running under it, in a manner that is
compatible with those provided by a
Java Enterprise Edition application server. The Java EE standard provides
a standard set of elements in the /WEB-INF/web.xml file to
reference/define resources.

See the following Specifications for more information about programming APIs
for JNDI, and for the features supported by Java Enterprise Edition (Java EE)
servers, which Tomcat emulates for the services that it provides:

web.xml configuration

The following elements may be used in the web application deployment
descriptor (/WEB-INF/web.xml) of your web application to define
resources:

<env-entry> - Environment entry, a
single-value parameter that can be used to configure how the application
will operate.

<resource-ref> - Resource reference,
which is typically to an object factory for resources such as a JDBC
DataSource, a JavaMail Session, or custom
object factories configured into Tomcat.

<resource-env-ref> - Resource
environment reference, a new variation of resource-ref
added in Servlet 2.4 that is simpler to configure for resources
that do not require authentication information.

Providing that Tomcat is able to identify an appropriate resource factory to
use to create the resource and that no further configuration information is
required, Tomcat will use the information in /WEB-INF/web.xml to
create the resource.

Tomcat provides a number of Tomcat specific options for JNDI resources that
cannot be specified in web.xml. These include closeMethod that
enables faster cleaning-up of JNDI resources when a web application stops and
singleton that controls whether or not a new instance of the
resource is created for every JNDI lookup. To use these configuration options
the resource must be specified in a web application's
<Context> element or in the
<GlobalNamingResources> element of
$CATALINA_BASE/conf/server.xml.

context.xml configuration

If Tomcat is unable to identify the appropriate resource factory and/or
additional configuration information is required, additional Tomcat specific
configuration must be specified before Tomcat can create the resource.
Tomcat specific resource configuration is entered in
the <Context> elements that
can be specified in either $CATALINA_BASE/conf/server.xml or,
preferably, the per-web-application context XML file
(META-INF/context.xml).

Tomcat specific resource configuration is performed using the following
elements in the <Context>
element:

<Environment> -
Configure names and values for scalar environment entries that will be
exposed to the web application through the JNDI
InitialContext (equivalent to the inclusion of an
<env-entry> element in the web application
deployment descriptor).

<Resource> -
Configure the name and data type of a resource made available to the
application (equivalent to the inclusion of a
<resource-ref> element in the web application
deployment descriptor).

<Transaction> -
Add a resource factory for instantiating the UserTransaction object
instance that is available at java:comp/UserTransaction.

Any number of these elements may be nested inside a
<Context> element and will
be associated only with that particular web application.

If a resource has been defined in a
<Context> element it is not
necessary for that resource to be defined in /WEB-INF/web.xml.
However, it is recommended to keep the entry in /WEB-INF/web.xml
to document the resource requirements for the web application.

Where the same resource name has been defined for a
<env-entry> element included in the web application
deployment descriptor (/WEB-INF/web.xml) and in an
<Environment> element as part of the
<Context> element for the
web application, the values in the deployment descriptor will take precedence
only if allowed by the corresponding
<Environment> element (by setting the override
attribute to "true").

Global configuration

Tomcat maintains a separate namespace of global resources for the
entire server. These are configured in the
<GlobalNamingResources> element of
$CATALINA_BASE/conf/server.xml. You may expose these resources to
web applications by using a
<ResourceLink> to
include it in the per-web-application context.

If a resource has been defined using a
<ResourceLink>, it is not
necessary for that resource to be defined in /WEB-INF/web.xml.
However, it is recommended to keep the entry in /WEB-INF/web.xml
to document the resource requirements for the web application.

Using resources

The InitialContext is configured as a web application is
initially deployed, and is made available to web application components (for
read-only access). All configured entries and resources are placed in
the java:comp/env portion of the JNDI namespace, so a typical
access to a resource - in this case, to a JDBC DataSource -
would look something like this:

Tomcat Standard Resource Factories

Tomcat includes a series of standard resource factories that can
provide services to your web applications, but give you configuration
flexibility (via the
<Context> element)
without modifying the web application or the deployment descriptor. Each
subsection below details the configuration and usage of the standard resource
factories.

NOTE - Of the standard resource factories, only the
"JDBC Data Source" and "User Transaction" factories are mandated to
be available on other platforms, and then they are required only if
the platform implements the Java Enterprise Edition (Java EE) specs.
All other standard resource factories, plus custom resource factories
that you write yourself, are specific to Tomcat and cannot be assumed
to be available on other containers.

Generic JavaBean Resources

0. Introduction

This resource factory can be used to create objects of any
Java class that conforms to standard JavaBeans naming conventions (i.e.
it has a zero-arguments constructor, and has property setters that
conform to the setFoo() naming pattern. The resource factory will
only create a new instance of the appropriate bean class every time a
lookup() for this entry is made if the singleton
attribute of the factory is set to false.

The steps required to use this facility are described below.

1. Create Your JavaBean Class

Create the JavaBean class which will be instantiated each time
that the resource factory is looked up. For this example, assume
you create a class com.mycompany.MyBean, which looks
like this:

2. Declare Your Resource Requirements

Next, modify your web application deployment descriptor
(/WEB-INF/web.xml) to declare the JNDI name under which
you will request new instances of this bean. The simplest approach is
to use a <resource-env-ref> element, like this:

Note that the resource name (here, bean/MyBeanFactory
must match the value specified in the web application deployment
descriptor. We are also initializing the value of the bar
property, which will cause setBar(23) to be called before
the new bean is returned. Because we are not initializing the
foo property (although we could have), the bean will
contain whatever default value is set up by its constructor.

Some beans have properties with types that can not automatically be
converted from a string value. Setting such properties using the Tomcat
BeanFactory will fail with a NamingException. In cases were those beans
provide methods to set the properties from a string value, the Tomcat
BeanFactory can be configured to use these methods. The configuration is
done with the forceString attribute.

The bean has two properties, both are of type InetAddress.
The first property local has an additional setter taking a
string argument. By default the Tomcat BeanFactory would try to use the
automatically detected setter with the same argument type as the property
type and then throw a NamingException, because it is not prepared to convert
the given string attribute value to InetAddress.
We can tell the Tomcat BeanFactory to use the other setter like that:

Multiple property descriptions can be combined in
forceString by concatenation with comma as a separator.
Each property description consists of either only the property name
in which case the BeanFactory calls the setter method. Or it consist
of name=method in which case the property named
name is set by calling method method.
For properties of types String or of primitive type
or of their associated primitive wrapper classes using
forceString is not needed. The correct setter will be
automatically detected and argument conversion will be applied.

UserDatabase Resources

0. Introduction

UserDatabase resources are typically configured as global resources for
use by a UserDatabase realm. Tomcat includes a UserDatabaseFactoory that
creates UserDatabase resources backed by an XML file - usually
tomcat-users.xml

The steps required to set up a global UserDatabase resource are described
below.

1. Create/edit the XML file

The XML file is typically located at
$CATALINA_BASE/conf/tomcat-users.xml however, you are free to
locate the file anywhere on the file system. It is recommended that the XML
files are placed in $CATALINA_BASE/conf. A typical XML would
look like:

The pathname attribute can be a URL, an absolute path or a
relative path. If relative, it is relative to $CATALINA_BASE.

The readonly attribute is optional and defaults to
true if not supplied. If the XML is writeable then it will be
written to when Tomcat starts. WARNING: When the file is
written it will inherit the default file permissions for the user Tomcat
is running as. Ensure that these are appropriate to maintain the security
of your installation.

3. Configure the Realm

JavaMail Sessions

0. Introduction

In many web applications, sending electronic mail messages is a
required part of the system's functionality. The
Java Mail API
makes this process relatively straightforward, but requires many
configuration details that the client application must be aware of
(including the name of the SMTP host to be used for message sending).

Tomcat includes a standard resource factory that will create
javax.mail.Session session instances for you, already
configured to connect to an SMTP server.
In this way, the application is totally insulated from changes in the
email server configuration environment - it simply asks for, and receives,
a preconfigured session whenever needed.

The steps required for this are outlined below.

1. Declare Your Resource Requirements

The first thing you should do is modify the web application deployment
descriptor (/WEB-INF/web.xml) to declare the JNDI name under
which you will look up preconfigured sessions. By convention, all such
names should resolve to the mail subcontext (relative to the
standard java:comp/env naming context that is the root of
all provided resource factories. A typical web.xml entry
might look like this:

Note that the application uses the same resource reference name
that was declared in the web application deployment descriptor. This
is matched up against the resource factory that is configured in the
<Context> element
for the web application as described below.

3. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the
<Context> element for
this web application.

Note that the resource name (here, mail/Session) must
match the value specified in the web application deployment descriptor.
Customize the value of the mail.smtp.host parameter to
point at the server that provides SMTP service for your network.

Additional resource attributes and values will be converted to properties
and values and passed to
javax.mail.Session.getInstance(java.util.Properties) as part of
the java.util.Properties collection. In addition to the
properties defined in Annex A of the JavaMail specification, individual
providers may also support additional properties.

If the resource is configured with a password attribute and
either a mail.smtp.user or mail.user attribute
then Tomcat's resource factory will configure and add a
javax.mail.Authenticator to the mail session.

4. Install the JavaMail libraries

Unpackage the distribution and place mail.jar into $CATALINA_HOME/lib so
that it is available to Tomcat during the initialization of the mail Session
Resource. Note: placing this jar in both $CATALINA_HOME/lib
and a web application's lib folder will cause an error, so ensure you have
it in the $CATALINA_HOME/lib location only.

5. Restart Tomcat

For the additional JAR to be visible to Tomcat, it is necessary for the
Tomcat instance to be restarted.

Example Application

The /examples application included with Tomcat contains
an example of utilizing this resource factory. It is accessed via the
"JSP Examples" link. The source code for the servlet that actually
sends the mail message is in
/WEB-INF/classes/SendMailServlet.java.

WARNING - The default configuration assumes that there
is an SMTP server listing on port 25 on localhost. If this is
not the case, edit the
<Context> element for
this web application and modify the parameter value for the
mail.smtp.host parameter to be the host name of an SMTP server
on your network.

JDBC Data Sources

0. Introduction

Many web applications need to access a database via a JDBC driver,
to support the functionality required by that application. The Java EE
Platform Specification requires Java EE Application Servers to make
available a DataSource implementation (that is, a connection
pool for JDBC connections) for this purpose. Tomcat offers exactly
the same support, so that database-based applications you develop on
Tomcat using this service will run unchanged on any Java EE server.

NOTE - The default data source support in Tomcat
is based on the DBCP connection pool from the
Commons
project. However, it is possible to use any other connection pool
that implements javax.sql.DataSource, by writing your
own custom resource factory, as described
below.

1. Install Your JDBC Driver

Use of the JDBC Data Sources JNDI Resource Factory requires
that you make an appropriate JDBC driver available to both Tomcat internal
classes and to your web application. This is most easily accomplished by
installing the driver's JAR file(s) into the
$CATALINA_HOME/lib directory, which makes the driver
available both to the resource factory and to your application.

2. Declare Your Resource Requirements

Next, modify the web application deployment descriptor
(/WEB-INF/web.xml) to declare the JNDI name under
which you will look up preconfigured data source. By convention, all such
names should resolve to the jdbc subcontext (relative to the
standard java:comp/env naming context that is the root of
all provided resource factories. A typical web.xml entry
might look like this:

<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the <Context>
configuration for the web application.
</description>
<res-ref-name>
jdbc/EmployeeDB
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>

WARNING - Be sure you respect the element ordering
that is required by the DTD for web application deployment descriptors!
See the
Servlet
Specification for details.

Note that the application uses the same resource reference name that was
declared in the web application deployment descriptor. This is matched up
against the resource factory that is configured in the
<Context> element for
the web application as described below.

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an element like this to the
<Context> element for
the web application.

driverClassName - Fully qualified Java class name
of the JDBC driver to be used.

username - Database username to be passed to our
JDBC driver.

password - Database password to be passed to our
JDBC driver.

url - Connection URL to be passed to our JDBC driver.
(For backwards compatibility, the property driverName
is also recognized.)

initialSize - The initial number of connections
that will be created in the pool during pool initialization. Default: 0

maxTotal - The maximum number of connections
that can be allocated from this pool at the same time. Default: 8

minIdle - The minimum number of connections that
will sit idle in this pool at the same time. Default: 0

maxIdle - The maximum number of connections that
can sit idle in this pool at the same time. Default: 8

maxWaitMillis - The maximum number of milliseconds that the
pool will wait (when there are no available connections) for a
connection to be returned before throwing an exception. Default: -1 (infinite)

Some additional properties handle connection validation:

validationQuery - SQL query that can be used by the
pool to validate connections before they are returned to the
application. If specified, this query MUST be an SQL SELECT
statement that returns at least one row.

testOnBorrow - true or false: whether a connection
should be validated using the validation query each time it is
borrowed from the pool. Default: true

testOnReturn - true or false: whether a connection
should be validated using the validation query each time it is
returned to the pool. Default: false

The optional evictor thread is responsible for shrinking the pool
by removing any connections which are idle for a long time. The evictor
does not respect minIdle. Note that you do not need to
activate the evictor thread if you only want the pool to shrink according
to the configured maxIdle property.

The evictor is disabled by default and can be configured using
the following properties:

timeBetweenEvictionRunsMillis - The number of
milliseconds between consecutive runs of the evictor.
Default: -1 (disabled)

numTestsPerEvictionRun - The number of connections
that will be checked for idleness by the evictor during each
run of the evictor. Default: 3

minEvictableIdleTimeMillis - The idle time in
milliseconds after which a connection can be removed from the pool
by the evictor. Default: 30*60*1000 (30 minutes)

testWhileIdle - true or false: whether a connection
should be validated by the evictor thread using the validation query
while sitting idle in the pool. Default: false

Another optional feature is the removal of abandoned connections.
A connection is called abandoned if the application does not return it
to the pool for a long time. The pool can close such connections
automatically and remove them from the pool. This is a workaround
for applications leaking connections.

The abandoning feature is disabled by default and can be configured
using the following properties:

maxOpenPreparedStatements - The maximum number of open
statements that can be allocated from the statement pool at the same time.
Default: -1 (unlimited)

defaultCatalog - The name of the default catalog.
Default: not set

connectionInitSqls - A list of SQL statements
run once after a Connection is created. Separate multiple statements
by semicolons (;). Default: no statement

connectionProperties - A list of driver specific
properties passed to the driver for creating connections. Each
property is given as name=value, multiple properties
are separated by semicolons (;). Default: no properties

Adding Custom Resource Factories

If none of the standard resource factories meet your needs, you can write
your own factory and integrate it into Tomcat, and then configure the use
of this factory in the
<Context> element for
the web application. In the example below, we will create a factory that only
knows how to create com.mycompany.MyBean beans from the
Generic JavaBean Resources example
above.

1. Write A Resource Factory Class

You must write a class that implements the JNDI service provider
javax.naming.spi.ObjectFactory interface. Every time your
web application calls lookup() on a context entry that is
bound to this factory (assuming that the factory is configured with
singleton="false"), the
getObjectInstance() method is called, with the following
arguments:

Object obj - The (possibly null) object containing
location or reference information that can be used in creating an object.
For Tomcat, this will always be an object of type
javax.naming.Reference, which contains the class name of
this factory class, as well as the configuration properties (from the
<Context> for the
web application) to use in creating objects to be returned.

Name name - The name to which this factory is bound
relative to nameCtx, or null if no name
is specified.

Context nameCtx - The context relative to which the
name parameter is specified, or null if
name is relative to the default initial context.

Hashtable environment - The (possibly null)
environment that is used in creating this object. This is generally
ignored in Tomcat object factories.

To create a resource factory that knows how to produce MyBean
instances, you might create a class like this:

In this example, we are unconditionally creating a new instance of
the com.mycompany.MyBean class, and populating its properties
based on the parameters included in the <ResourceParams>
element that configures this factory (see below). You should note that any
parameter named factory should be skipped - that parameter is
used to specify the name of the factory class itself (in this case,
com.mycompany.MyBeanFactory) rather than a property of the
bean being configured.

You will need to compile this class against a class path that includes
all of the JAR files in the $CATALINA_HOME/lib directory. When you are through,
place the factory class (and the corresponding bean class) unpacked under
$CATALINA_HOME/lib, or in a JAR file inside
$CATALINA_HOME/lib. In this way, the required class
files are visible to both Catalina internal resources and your web
application.

2. Declare Your Resource Requirements

Next, modify your web application deployment descriptor
(/WEB-INF/web.xml) to declare the JNDI name under which
you will request new instances of this bean. The simplest approach is
to use a <resource-env-ref> element, like this:

Note that the resource name (here, bean/MyBeanFactory
must match the value specified in the web application deployment
descriptor. We are also initializing the value of the bar
property, which will cause setBar(23) to be called before
the new bean is returned. Because we are not initializing the
foo property (although we could have), the bean will
contain whatever default value is set up by its constructor.

You will also note that, from the application developer's perspective,
the declaration of the resource environment reference, and the programming
used to request new instances, is identical to the approach used for the
Generic JavaBean Resources example. This illustrates one of the
advantages of using JNDI resources to encapsulate functionality - you can
change the underlying implementation without necessarily having to
modify applications using the resources, as long as you maintain
compatible APIs.