[英]How to get resource from the context.xml file in tomcat webapp?
這是我的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"
/>
...
我已經嘗試使用ServletContext.getResource(java.lang.String)和資源名稱(“jdbc / MyDatasource”),但Tomcat抱怨該名稱不以'/'開頭。 我也試過“/ jdbc / MyDatasource”,但這次它返回null。
我主要需要jdbcUrl與數據庫服務器進行連接檢查 (查看服務器是否在線且可操作)。
關鍵字是:JNDI。 context.xml
中的資源不是“系統資源”,而是JNDI資源。 嘗試這個:
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();
您應該能夠使用以下代碼訪問數據源:
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.