Search code examples
javatomcatamazon-ec2jndijtds

Tomcat 8 configuration for JTDS DataSource


I'm new to setting up DataSources with Tomcat 8 and am having trouble. Here is my config:

WEB-INF/web.xml

<web app ... >
  <servlet> ... </servlet>
  <servlet-mapping> ... </servlet-mapping>
  ...
  <resource-ref>
     <description>My DB</description>
     <res-ref-name>jdbc/mydb</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

WEB-INF/context.xml

<Context>
  <Resource name="jdbc/mydb"
      auth="Container"
      type="javax.sql.DataSource"
      username="xirt"
      password="*******"
      driverClassName="net.sourceforge.jtds.jdbc.Driver"
      url="jdbc:jtds:sqlserver://xirt.rds.amazonaws.com:1433/mydb"
      maxActive="15"
      maxIdle="3" />
</Context>

Program Code:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/mydb");
System.out.println("DataSource: "+ds);
Connection connection = ds.getConnection();

I am running on Amazon EC2, so have installed tomcat8 using yum:

sudo yum install java-1.8.0
sudo yum install tomcat8

I have been getting the following errors:

  1. ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
    • this appears to be resolved by copying tomcat-dbcp.jar from the apache-tomcat-8.0.36.zip file from their website to $CATALINA_HOME/lib

Then:

  1. java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'

I am going out of my mind with this one...!

To reproduce, one simply has to spin up an AMI instance on AWS, install the JTDS driver and try connecting to a SQL server.


Solution

  • Turns out it was much more straightforward.

    The context.xml file needs to be placed in the META-INF/ subdirectory, not the WEB-INF/ subdirectory within the .war file.