SE452: Using JNDI in Tomcat [3/18] ![]() ![]() ![]() |
Examples:
web.xml
edits
<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 (or the context.xml file supplied and placed in the conf/Catalina/localhost directory). </description> <res-ref-name>jdbc/EmployeeDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
Make sure the ordering is in conformance to the web application deployment descriptor DTD! (You can probably put it at the end of your file)
Setup your server.xml (or add a config.xml snippet to your conf/Catalina/localhost
directory) with the settings for the DataSource
Factory for
your database
<!-- Document : Context.xml Created on : September 22, 2003, 10:00 PM Author : Matthew Wright Description: A context node for this webapp. --> <Context path="/se452" docBase="se452" debug="9"> <Resource name="jdbc/EmployeeDB" auth="Container" type="javax.sql.DataSource"/> <ResourceParams name="jdbc/EmployeeDB"> <parameter> <name>username</name> <value>sa</value> </parameter> <parameter> <name>password</name> <value></value> </parameter> <parameter> <name>driverClassName</name> <value>org.hsqldb.jdbcDriver</value> </parameter> <parameter> <name>url</name> <value>jdbc:hsqldb:hsql:c:\temp\hw</value> </parameter> <parameter> <name>maxActive</name> <value>8</value> </parameter> <parameter> <name>maxIdle</name> <value>4</value> </parameter> </ResourceParams> </Context>
Now, use JNDI code to get the InitialContext
and obtain a
reference to the DataSource
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();