Using JNDI

J2EE defines an even more flexible way to make a DataSource, or any other shared resource, available through a Java Naming and Directory Interface (JNDI) service. Through JNDI, the connection pool is available to all parts of the application, even to components that don’t have access to the servlet context. This should therefore be your first choice for resource sharing, unless you need to target containers that don’t support JNDI. All J2EE-compliant application servers support JNDI, and many pure web containers (containers without EJB support), such as Tomcat, JRun, Resin, and ServletExec, provide resource access through JNDI even though the servlet and JSP specifications don’t require it.

To use JNDI, you first define the resource in the web application deployment descriptor, using the <resource-ref> element:

<web-app ...>
  ...
  <resource-ref>
    <description>
      JNDI DataSource for example database
    </description>
    <res-ref-name>jdbc/Example</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Sharable</res-sharing-scope>
  </resource-ref>

The optional <description> element describes the resource and may be used to help the person that deploys the application.

The <res-ref-name> element is mandatory and must contain the unique name that the application components use to retrieve the resource, as you will see shortly. For a data-source resource, the J2EE specification recommends that you use the naming convention shown here, i.e., ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.