如何从tomcat Webapp中的context.xml文件获取资源? [英] How to get resource from the context.xml file in tomcat webapp?
本文介绍了如何从tomcat Webapp中的context.xml文件获取资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的 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 '/'. I also tried with "/jdbc/MyDatasource", but this time it returns null.
我主要需要 jdbcUrl 来执行与数据库服务器的连接检查(请查看服务器是否在线且可运行).
I mainly need the jdbcUrl to perform a connection check with the database server (see if the server is online and operational).
推荐答案
关键字是:JNDI. context.xml
中的资源不是系统资源",而是JNDI资源.
试试这个:
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();
这篇关于如何从tomcat Webapp中的context.xml文件获取资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文