问题
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).
回答1:
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();
回答2:
You should be able to access the datasource with the following code:
Context initialContext = new InitialContext();
Context envContext = (Context)initialContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MyDatasource");
来源:https://stackoverflow.com/questions/8298132/how-to-get-resource-from-the-context-xml-file-in-tomcat-webapp