The Jakarta Project
      The Tomcat Servlet/JSP Container

Links

Getting Started

Administrators

Application Developers

Catalina Developers

Jasper Developers

JNDI Resources HOW-TO

Introduction

Tomcat 4 provides a JNDI InitialContext implementation instance to web applications running under it, in a manner that is compatible with those provided by a Java2 Enterprise Edition application server. Entries in this InitialContext are configured in the $CATALINA_HOME/conf/server.xml file, and may be referenced by the following elements in the web application deployment descriptor (/WEB-INF/web.xml) of your web application:

  • <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 4.
  • <resource-env-ref> - Resource environment reference, a new variation of resource-ref added in Servlet 2.3 that is simpler to configure for resources that do not require authentication information.

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 will be 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:

// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// Look up our data source
DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

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

Configuring JNDI Resources

Each available JNDI Resource is configured based on inclusion of the following elements in the $CATALINA_HOME/conf/server.xml file:

  • <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).
  • <ResourceParams> - Configure the Java class name of the resource factory implementation to be used, as well as JavaBeans properties used to configure that resource factory.

Any number of these elements may be nested inside a <Context> element (to be associated only with that particular web application) or inside a <DefaultContext> element (used to set the default configuration characteristics for automatically deloyed applications).

In addition, the names and values of all <env-entry> elements included in the web application deployment descriptor (/WEB-INF/web.xml) are configured into the initial context as well, overriding corresponding values from conf/server.xml only if allowed by the corresponding <Environment> element (by setting the override attribute to "true").

Tomcat Standard Resource Factories

Tomcat 4 includes a series of standard resource factories that can provide services to your web applications, but give you configuration flexibility (in $CATALINA_HOME/conf/server.xml) without modifying the web application or the deployment descriptor. Each subsection below details the configuration and usage of the standard resource factories.

See Adding Custom Resource Factories for information about how to create, install, configure, and use your own custom resource factory classes with Tomcat 4.

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 Java2 Enterprise Edition (J2EE) 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 create a new instance of the appropriate bean class every time a lookup() for this entry is made.

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:

package com.mycompany;

public class MyBean {

  private String foo = "Default Foo";

  public String getFoo() {
    return (this.foo);
  }

  public void setFoo(String foo) {
    this.foo = foo;
  }

  private int bar = 0;

  public int getBar() {
    return (this.bar);
  }

  public void setBar(int bar) {
    this.bar = bar;
  }


}

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:

<resource-env-ref>
  <Description>
    Object factory for MyBean instances.
  </Description>
  <resource-env-ref-name>
    bean/MyBeanFactory
  </resource-env-ref-name>
  <resource-env-ref-type>
    com.mycompany.MyBean
  </resource-env-ref-type>
<resource-env-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.

3. Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the $CATALINA_HOME/conf/server.xml file, nested inside the Context element for this web application (or nested inside a DefaultContext element for the surrounding <Host> or <Engine> element.

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"/>
  <ResourceParams name="bean/MyBeanFactory">
    <parameter>
      <name>factory</name>
      <value>org.apache.naming.factory.BeanFactory</value>
    </parameter>
    <parameter>
      <name>bar</name>
      <value>23</value>
    </parameter>
  </ResourceParams>
  ...
</Context>

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.

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 4 includes a standard resource factory that will create javax.mail.Session session instances for you, already connected to the SMTP server that is configured in server.xml. 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:

<resource-ref>
  <description>
    Resource reference to a factory for javax.mail.Session
    instances that may be used for sending electronic mail
    messages, preconfigured to connect to the appropriate
    SMTP server.
  </description>
  <res-ref-name>
    mail/Session
  </res-ref-name>
  <res-type>
    javax.mail.Session
  </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.

2. Code Your Application's Use Of This Resource

A typical use of this resource reference might look like this:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from"));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);

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 $CATALINA_HOME/conf/server.xml, as described below.

3. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the $CATALINA_HOME/conf/server.xml file, nested inside the Context element for this web application (or nested inside a DefaultContext element for the surrounding <Host> or <Engine> element.

<Context ...>
  ...
  <Resource name="mail/Session" auth="Container"
            type="javax.mail.Session"/>
  <ResourceParams name="mail/Session">
    <parameter>
      <name>mail.smtp.host</name>
      <value>localhost</value>
    </parameter>
  </ResourceParams>
  ...
</Context>

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.

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 $CATALINA_HOME/conf/server.xml file, 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 J2EE Platform Specification requires J2EE Application Servers to make available a DataSource implementation (that is, a connection pool for JDBC connections) for this purpose. Tomcat 4 offers exactly the same support, so that database-based applications you develop on Tomcat using this service will run unchanged on any J2EE server.

For information about JDBC, you should consult the following:

NOTE - The default data source support in Tomcat supports Tyrex. 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/common/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 server.xml file.
  </description>
  <res-ref-name>
    jdbc/EmployeDB
  </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.

3. Code Your Application's Use Of This Resource

A typical use of this resource reference might look like this:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

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 $CATALINA_HOME/conf/server.xml, as described below.

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the $CATALINA_HOME/conf/server.xml file, nested inside the Context element for this web application (or nested inside a DefaultContext element for the surrounding <Host> or <Engine> element.

<Context ...>
  ...
  <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource"/>
  <ResourceParams name="jdbc/EmployeeDB">
    <parameter>
      <name>user</name>
      <value>dbusername</value>
    </parameter>
    <parameter>
      <name>password</name>
      <value>dbpassword</value>
    </parameter>
    <parameter>
      <name>driverClassName</name>
      <value>org.hsql.jdbcDriver</value>
    </parameter>
    <parameter>
      <name>driverName</name>
      <value>jdbc:HypersonicSQL:database</value>
    </parameter>
  </ResourceParams>
  ...
</Context>

Note that the resource name (here, jdbc/EmployeeDB) 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.

This example assumes that you are using the HypersonicSQL database JDBC driver. Customize the driverClassName and driverName parameters to match your actual database's JDBC driver and connection URL.

User Transactions

If you utilize Tyrex for your JDBC resource factory as described above, you will also have support for the java.transaction.UserTransaction resource provided by Tyrex (since it is XA-capable). To use this feature, code your application as follows:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Transaction tx = (Transaction) envCtx.lookup("UserTransaction");

tx.begin();
... perform transactional operations on data ...
tx.commit();

This is useful when you need to do "two-phased commits" across more than one database, where the commit needs to either succeed completely or fail completely across all associated databases. This feature requires a JDBC driver that also supports XA capabilities. See the J2EE and JDBC documentation for more information.

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 4, and then configure the use of this factory in the conf/server.xml configuration file. 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 inteface. Every time your web application calls lookup() on a context entry that is bound to this factory, 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 conf/server.xml) 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:

package com.mycompany;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name, Context nameCtx, Hashtable environment)
      throws NamingException {

      // Acquire an instance of our specified bean class
      MyBean bean = new MyBean();

      // Customize the bean properties from our attributes
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name = addr.getType();
          String value = (String) addr.getContent();
          if (name.equals("foo")) {
              bean.setFoo(value);
          } else if (name.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // Return the customized instance
      return (bean);

  }

}

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.

For more information about ObjectFactory, see the JNDI 1.2 Service Provider Interface (SPI) Specification.

You will need to compile this class against a class path that includes all of the JAR files in the $CATALINA_HOME/common/lib and $CATALINA_HOME/server/lib directories. When you are through, place the factory class (and the corresponding bean class) unpacked under $CATALINA_HOME/common/classes, or in a JAR file inside $CATALINA_HOME/common/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:

<resource-env-ref>
  <description>
    Object factory for MyBean instances.
  </description>
  <resource-env-ref-name>
    bean/MyBeanFactory
  </resource-env-ref-name>
  <resource-env-ref-type>
    com.mycompany.MyBean
  </resource-env-ref-type>
<resource-env-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.

3. Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an elements like this to the $CATALINA_HOME/conf/server.xml file, nested inside the Context element for this web application (or nested inside a DefaultContext element for the surrounding <Host> or <Engine> element.

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"/>
  <ResourceParams name="bean/MyBeanFactory">
    <parameter>
      <name>factory</name>
      <value>com.mycompany.MyBeanFactory</value>
    </parameter>
    <parameter>
      <name>bar</name>
      <value>23</value>
    </parameter>
  </ResourceParams>
  ...
</Context>

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.


Copyright © 1999-2002, Apache Software Foundation