Sunday, June 14, 2009

Getting Database Connection Using JNDI and JDBC Datasource in Tomcat


Tomcat 5 provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java2 Enterprise Edition application server. The J2EE standard provides a standard set of elements in the /WEB-INF/web.xmlfile to reference resources; resources referenced in these elements must be defined in an application-server-specific configuration.
For Tomcat 5, these entries in per-web-application InitialContext are configured in the elements that can be specified in either$CATALINA_HOME/conf/server.xml or, preferably, the per-web-application context XML file (either META-INF/context.xml).
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 are 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();


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.
...

<Resource name="jdbc/db1"
auth
="Container" type="javax.sql.DataSource"
maxActive
="100" maxIdle="30" maxWait="10000" username="root"
password
="anu" driverClassName="com.mysql.jdbc.Driver"
url
="jdbc:mysql://localhost:3306/DB1?autoReconnect=true" />


Click for private tuition by a professional