javatomcatweb-applicationsjndicontext.xml

How to get resource from the context.xml file in tomcat webapp?


This is my context.xml file:

...
<Resource auth="Container"
          driverClass="net.sourceforge.jtds.jdbc.Driver"
          type="com.jolbox.bonecp.BoneCPDataSource"
          idleMaxAge="240"
          idleConnectionTestPeriod="60"
          partitionCount="3"
          acquireIncrement="1"
          maxConnectionsPerPartition="10"
          minConnectionsPerPartition="3"
          statementsCacheSize="50"
          releaseHelperThreads="4"

          name="jdbc/MyDatasource"
          username="my_username"
          password="my_password"
          factory="org.apache.naming.factory.BeanFactory"
          jdbcUrl="jdbc:jtds:sqlserver://localhost:12345/my_database"
/>
...

I already tried using ServletContext.getResource(java.lang.String) with the name of the resource ("jdbc/MyDatasource"), but Tomcat complains that the name doesn't begin with a '/'. I also tried with "/jdbc/MyDatasource", but this time it returns null.

I mainly need the jdbcUrl to perform a connection check with the database server (see if the server is online and operational).


Solution

  • Keyword is: JNDI. The resources in the context.xml are not 'System Resources' but JNDI Resources. Try this:

    InitialContext ic = new InitialContext();
    // that's everything from the context.xml and from the global configuration
    Context xmlContext = (Context) ic.lookup("java:comp/env");
    DataSource myDatasource = (DataSource) xmlContext.lookup("jdbc/MyDatasource");
    
    // now get a connection to see if everything is fine.
    Connection con = ds.getConnection();
    // reaching this point means everything is fine.
    con.close();