None

Java JDNI Database Access

April 12, 2010

Here's the Java code and config required to set up a database connection in tomcat, and then refer to it from a WAR file.

Java Code

This code lives inside the WAR file. It looks at Tomcat's config to work out which database to connect to, connects, and then returns a connection object.

public static Connection getConnection()
{
  Connection lConnection = null;

  try
  {
    InitialContext lContext = new InitialContext();

    String lLookupURI = "java:comp/env/jdbc/DataSourceDS";
    Object lDataSource = lContext.lookup(lLookupURI);

    lConnection = ((javax.sql.DataSource) lDataSource).getConnection();
    lConnection.setAutoCommit(false);
  }
  catch (Exception lException)
  {
    throw new RuntimeException(lException.getMessage(), lException);
  }

  return lConnection;
}

web.xml

This is also inside the war file, and advertises the fact that the WAR file needs a database datasource of this name setting up.

<resource-ref>
  <res-ref-name>jdbc/DataSourceDS</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

Tomcat 6 server.xml

The server.xml file in Tomcat is changed to supply details for the database connection called DataSourceDS.

<Resource auth="Container" 
          name="jdbc/DataSourceDS" 
          type="javax.sql.DataSource" 
          url="jdbc:postgresql://server:5432/database" 
          password="password" 
          maxActive="4" 
          maxWait="5000" 
          driverClassName="org.postgresql.Driver" 
          username="username" 
          maxIdle="2" />

Tomcat 6 context.xml

We also need to link this in the context.xml file of Tomcat 6.

<ResourceLink name="jdbc/DataSourceDS" global="jdbc/DataSourceDS" type="javax.sql.DataSource" />

Tags: java tomcat jndi jdbc