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 ...>
      JNDI DataSource for example database

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.