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;