01
Sep
09

JNDI configuration on Apache Tomcat 6.0


This page describes how to setup JDBC Resources in Tomcat 6.

Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Database Drivers

Place the database driver jar file into the server/lib folder.

Define the resource in Tomcat

Place the following into the $CATALINA_BASE/conf/context.xml

  <Resource name="jdbc/batch" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="username" password="password" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/batch"/>

Please note that if you are running in Eclipse and have Tomcat 6 setup as a WTP project then this file is located in the “Server” project in your eclipse workspace.

Create the resource reference

The following step is important since every application server has their own JNDI Namespace. Defining the resource reference ensures that you don’t tie your application to a particular proprietary implementation. (See my post on JNDI JBoss 5)

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
	<servlet-name>TestServlet</servlet-name>
	<servlet-class>com.test.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>TestServlet</servlet-name>
	<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
 
<resource-ref>
 <description>Recipe Database</description>
 <res-ref-name>jdbc/batch</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 </resource-ref>

</web-app>

Test using Snoop JSP

To test the datasource simply create a snoop jsp to perform a lookup.

Test using your own Servlet

src/main/java/com/test/TestServlet.java

package com.test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//You may use the following lines to initialize the context.
		// Obtain our environment naming context
		Context initCtx;
		try {
			initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			 
			//A data source can be obtained by doing the following.
			// Look up our data source
			DataSource ds = (DataSource) envCtx.lookup("jdbc/batch");
			 
			// Allocate and use a connection from the pool
			Connection conn = ds.getConnection();
			//... use this connection to access the database ...
			System.out.println("connected: " + !conn.isClosed());
			
			conn.close();		
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

If you are using the popular spring framework you can do the following


<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/batch"/>
    <property name="resourceRef" value="true"/>
 </bean>
Full downloadable source for this page is available here.
About these ads

5 Responses to “JNDI configuration on Apache Tomcat 6.0”


  1. 1 Sa
    January 16, 2012 at 8:34 am

    Hi,

    Thanx for such a nice article. Please continue to write such things which are very much helpful and time saving.
    We have an application where we need to initiallize the datasource at server start up. Could you please suggest a way to do that ?

  2. 2 RedFox
    February 6, 2012 at 3:08 am

    Thanks for providing such a great article.

  3. 3 Joe
    February 18, 2013 at 10:43 am

    can’t seem to get the “Test using your own Servlet” to work.
    Have you tested it?
    in the line: “Context initCtx = new InitialContext();”
    seems I can’t convert intialContext to Context?
    Any help would be appreciated.

    • February 18, 2013 at 11:01 pm

      Just tested it again. Worked fine.
      Not sure if this might help but a common mistake is to modify the wrong context.xml file, Please note that if you are running in Eclipse and have Tomcat 6 setup as a WTP project then the context.xml file is located in the “Server” project in your eclipse workspace.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 54 other followers

September 2009
S M T W T F S
« Aug   Oct »
 12345
6789101112
13141516171819
20212223242526
27282930  

Blog Stats

  • 529,517 hits

Follow

Get every new post delivered to your Inbox.

Join 54 other followers

%d bloggers like this: