DB2 datasource configuration for Tomcat 6

Today I spent a bit of time figuring out how to configure a DB2 datasource within Tomcat 6 and thought I’d share the information in case someone else is interested. Honestly I’m not sure if there is really anything DB2-specific here as it seems pretty generic but DB2 is what I’m using on this project so that’s how I’m approaching this.

It’s been awhile since I’ve needed to define a datasource in Tomcat but I’m working on a proof-of-concept where Websphere is total overkill.  A bit of googling brought up this page which had exactly what I needed.   A bit of experimentation, however, allowed me to find some simplication of those instructions.   Here is what I did.

In the Tomcat server.xml configuration file located in


add a Resource similar to the following:

<Resource auth="Container"
     password="xxxxx" />

Next we need to create a ResourceLink that a deployed application will reference to get to this JNDI resource. In context.xml also located in


add something similar to the following:

Unlike the reference article there is no need to add a resource reference to the web.xml for the application.

When looking up the datasource (or referencing it in a Spring config, etc.) you simply look up “MyDatasource” as defined in the link in context.xml. In other words:

try {
	Context initCtx = new InitialContext();
	Context envCtx = (Context) initCtx.lookup("java:comp/env");
	DataSource ds = (DataSource) envCtx.lookup("MyDatasource");
	Connection c = ds.getConnection();
        } catch (NamingException e) {
        } catch (SQLException e) {
%d bloggers like this: