简体   繁体   English

如何从tomcat webapp中的context.xml文件获取资源?

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

This is my context.xml file: 这是我的context.xml文件:

...
<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 '/'. 我已经尝试使用ServletContext.getResource(java.lang.String)和资源名称(“jdbc / MyDatasource”),但Tomcat抱怨该名称不以'/'开头。 I also tried with "/jdbc/MyDatasource", but this time it returns null. 我也试过“/ jdbc / MyDatasource”,但这次它返回null。

I mainly need the jdbcUrl to perform a connection check with the database server (see if the server is online and operational). 我主要需要jdbcUrl与数据库服务器进行连接检查 (查看服务器是否在线且可操作)。

Keyword is: JNDI. 关键字是:JNDI。 The resources in the context.xml are not 'System Resources' but JNDI Resources. context.xml中的资源不是“系统资源”,而是JNDI资源。 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();

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM