Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Add a permalink. Fix formatting. Convert links to https.

Permalink to this page:

How do I use DataSources with Tomcat?

When developing J2EE JavaEE web applications, the task of database connection management can be daunting. Best practice involves using a J2EE JavaEE DataSource to provide connection pooling, but configuring DataSources in web application servers and connecting your application to them is often a cumbersome process and poorly documented.


With Tomcat the process is vastly simplified. Tomcat allows you to configure DataSources for your J2EE JavaEE web application in a context.xml file that is stored in your web application project. You don't have to mess with configuring the DataSource separately in the Tomcat server.xml, or referencing it in your application's web.xml file. Here's how:


Install the .jar file(s) containing the JDBC driver in Tomcat's $CATALINA_BASE/lib folder. You do not need to put them in your application's WEB-INF/lib folder. When working with J2EE JavaEE DataSources, the web application server manages connections for your application.


In the root of your web app directory structure, create a folder named META-INF (all caps). Inside that folder, create a file named context.xml that contains a Resource like this:

No Format

<?xml version="1.0" encoding="UTF-8"?>


  <Resource name="jdbc/WallyDB" auth="Container"
            type="javax.sql.DataSource" username="wally" password="wally"


This example shows how to configure a DataSource for a SQL Server database named mytest located on the development machine. Simply edit the Resource name, driverClassName, username, password, and url to provide values appropriate for your JDBC driver.

Access the DataSource in Your Application

From a Servlet

Here's how you might access the data in a servlet:

No Format

  InitialContext ic = new InitialContext();
  DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/WallyDB");
  Connection c = ds.getConnection();


Known-Working examples for other Databases

No Format

    <Resource name="jdbc/denali" auth="Container" type="javax.sql.DataSource"
              username="denali" url="jdbc:postgresql://localhost:5432/demo"
              maxActive="20" maxIdle="10"/>

No Format

    <Resource name="jdbc/ccsdatasource" auth="Container" type="javax.sql.DataSource"
              username="ccs" password="secret" url="jdbc:mysql://localhost:3306/ccs"
              maxActive="20" maxIdle="10"/>


This technique is Tomcat-specific. If you deploy your web application to another application server, you will need to configure the database according to your application server's documentation, and reference it in your application's web.xml.CategoryFAQ