Sun Java System Web Server 7.0 Update 4 Developer's Guide to Java Web Applications

Using JNDI to Access the jdbc-resource Within a Web Application

Using JNDI, a web application can access a JDBC connection pool by looking up the jdbc-resource that configures it. The jdbc-resources can access the name in its web descriptor. The following web descriptors example refer to the connection pool created in the earlier example.

WEB-INF/web.xml

<web-app>
...
  <resource-ref>
    <description>JDBC Connection Pool</description>
    <res-ref-name>jdbc/myJdbc</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
...
</web-app>

WEB-INF/sun-web.xml

<sun-web-app>
...
		<resource-ref>
			<res-ref-name>jdbc/myJdbc</res-ref-name>
			<jndi-name>jdbc/MyPool</jndi-name>
		</resource-ref>
...
</sun-web-app>

In the above example, jdbc/myJdbc is the name by which the pool is referenced in the web application and jdbc/MyPool is the JNDI name of the jdbc-resources configuration.

The following is an example for using the pool in a web application.

Context initContext = new InitialContext();
Context webContext = (Context)initContext.lookup("java:/comp/env");

DataSource ds = (DataSource) webContext.lookup("jdbc/myJdbc");
Connection dbCon = ds.getConnection();