Tomcat4(5)提供了一個與Java Enterprise Edition應用服務相相容的JNDI--InitialContext實現執行個體。它的初始資料設定在$CATALINA_HOME/conf/server.xml檔案裡。並可能在網頁應用環境描述(/WEB-INF/web.xml)裡被下列元素引用:
<resource-ref>--資源參數,一般是資料庫驅動程式、JavaMail Session、自訂類工廠等。
在$CATALINA_HOME/conf/server.xml裡設定資料庫連接池:
下面是tomcat配置範例的代碼,必須放在<Host>和</Host>之間。
<!-- Tomcat Examples Context -->
<Context path="/examples" docBase="examples.war" debug="0"
reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_examples_log." suffix=".txt"
timestamp="true"/>
<Ejb name="ejb/EmplRecord" type="Entity"
home="com.wombat.empl.EmployeeRecordHome"
remote="com.wombat.empl.EmployeeRecord"/>
<!-- If you wanted the examples app to be able to edit the
user database, you would uncomment the following entry.
Of course, you would want to enable security on the
application as well, so this is not done by default!
The database object could be accessed like this:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
UserDatabase database =
(UserDatabase) envCtx.lookup("userDatabase");
-->
<!--
<ResourceLink name="userDatabase" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/>
-->
<!-- PersistentManager: Uncomment the section below to test Persistent
Sessions.
saveOnRestart: If true, all active sessions will be saved
to the Store when Catalina is shutdown, regardless of
other settings. All Sessions found in the Store will be
loaded on startup. Sessions past their expiration are
ignored in both cases.
maxActiveSessions: If 0 or greater, having too many active
sessions will result in some being swapped out. minIdleSwap
limits this. -1 or 0 means unlimited sessions are allowed.
If it is not possible to swap sessions new sessions will
be rejected.
This avoids thrashing when the site is highly active.
minIdleSwap: Sessions must be idle for at least this long
(in seconds) before they will be swapped out due to
activity.
0 means sessions will almost always be swapped out after
use - this will be noticeably slow for your users.
maxIdleSwap: Sessions will be swapped out if idle for this
long (in seconds). If minIdleSwap is higher, then it will
override this. This isn't exact: it is checked periodically.
-1 means sessions won't be swapped out for this reason,
although they may be swapped out for maxActiveSessions.
If set to >= 0, guarantees that all sessions found in the
Store will be loaded on startup.
maxIdleBackup: Sessions will be backed up (saved to the Store,
but left in active memory) if idle for this long (in seconds),
and all sessions found in the Store will be loaded on startup.
If set to -1 sessions will not be backed up, 0 means they
should be backed up shortly after being used.
To clear sessions from the Store, set maxActiveSessions, maxIdleSwap,
and minIdleBackup all to -1, saveOnRestart to false, then restart
Catalina.
-->
<!--
<Manager className="org.apache.catalina.session.PersistentManager"
debug="0"
saveOnRestart="true"
maxActiveSessions="-1"
minIdleSwap="-1"
maxIdleSwap="-1"
maxIdleBackup="-1">
<Store className="org.apache.catalina.session.FileStore"/>
</Manager>
-->
<Environment name="maxExemptions" type="java.lang.Integer"
value="15"/>
<Parameter name="context.param.name" value="context.param.value"
override="false"/>
<Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/EmployeeAppDb">
<parameter><name>username</name><value>sa</value></parameter>
<parameter><name>password</name><value></value></parameter>
<parameter><name>driverClassName</name>
<value>org.hsql.jdbcDriver</value></parameter>
<parameter><name>url</name>
<value>jdbc:HypersonicSQL:database</value></parameter>
</ResourceParams>
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"/>
<ResourceParams name="mail/Session">
<parameter>
<name>mail.smtp.host</name>
<value>localhost</value>
</parameter>
</ResourceParams>
<ResourceLink name="linkToGlobalResource"
global="simpleValue"
type="java.lang.Integer"/>
</Context>
下面是一些參數的說明:
<Context path="/test" docBase="test" debug="0" reloadable="true" crossContext="true">
其中:
1) path 指定路徑,這裡設定的是$CATALINA_HOME/webapps下的test目錄;
2) docBase 檔案根目錄。
3) reloader 當網頁被更新時是否重新編譯。
4) maxActive 串連池的最大資料庫連接數。設為0表示無限制。
5) maxIdle 資料庫連接的最大空閑時間。超過此空閑時間,資料庫連接將被標記為不可用,然後被釋放。設為0表示無限制。
6) maxWait 最大建立串連等待時間。如果超過此時間將接到異常。設為-1表示無限制。
7) removeAbandoned 回收被遺棄的(一般是忘了釋放的)資料庫連接到串連池中。
8) removeAbandonedTimeout 資料庫連接過多長時間不用將被視為被遺棄而收回串連池中。
9) logAbandoned 將被遺棄的資料庫連接的回收記入日誌。
10) driverClassName JDBC驅動程式。
11) url 資料庫連接字串
通過對例子的分析不難看出,實際上需要修改的地方不多。主要的元素包括驅動名稱driverClassName、連接字串url以及串連的使用者和密碼,同時指定應用程式套件組合路徑即可。
產生文檔如下:
<Context path="/lottery" docBase="lottery" debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/toni" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/toni">
<parameter>
<name>maxActive</name>
<!-- Maximum number of DB connections in pool.Set to 0 for no limit. -->
<value>10</value>
</parameter>
<parameter>
<name>maxIdle</name>
<!-- Maximum number of idle DB connections to retain in pool.Set to 0 for no limit. -->
<value>5</value>
</parameter>
<parameter>
<name>maxWait</name>
<!-- Maximum time to wait for a DB connection to become available in ms.An exception is thrown if this timeout is exceeded.Set to -1 to wait indefinitely. -->
<value>10000</value>
</parameter>
<parameter>
<name>removeAbandoned</name>
<!-- Abandoned DB connections are removed and recycled -->
<value>true</value>
</parameter>
<parameter>
<name>removeAbandonedTimeout</name>
<!-- Use the removeAbandonedTimeout parameter to set the number of seconds a DB connection has been idle before it is considered abandoned. -->
<value>60</value>
</parameter>
<parameter>
<name>username</name>
<!-- Database User Name -->
<value>scott</value>
</parameter>
<parameter>
<name>password</name>
<!-- User Password -->
<value>tiger</value>
</parameter>
<parameter>
<name>driverClassName</name>
<!-- Database Driver Class Name -->
<value>oracle.jdbc.driver.OracleDriver</value>
</parameter>
<parameter>
<name>url</name>
<!-- Database Address -->
<value>jdbc:oracle:thin:@127.0.0.1:1521:toni</value>
</parameter>
</ResourceParams>
</Context>
與之相配合的應用程式的配置文檔在$CATALINA_HOME/webapps/test/WEB-INF/web.xml裡設定被引用的資源:
下面是配置代碼,必須放在<web-app>和</web-app>裡。
<!-- Database Config start -->
<resource-ref>
<description>connectDB test</description>
<res-ref-name>jdbc/toni</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- Database Config end -->
下面是一下參數的必要說明:
1) description 對被引用的資源的描述。
2) res-ref-name 資源名稱。見上面的<ResourceParams name="jdbc/toni">
3) res-type 資源類型。見上面的<Resource name="jdbc/toni" auth="Container" type="javax.sql.DataSource"/>
在程式中使用的方法與其他的應用大體相同。
Context ctx=null;
Connection cnn=null;
ctx=new InitialContext();
if(ctx==null)
throw new Exception("沒有匹配的環境");
DataSource ds=(DataSource)ctx.lookup(url);
if(ds==null)
throw new Exception("沒有匹配資料庫");
cnn=ds.getConnection();
return cnn;