JNDI是J2EE中一个很重要的标准,通常我们是在EJB编程中用到,
Tomcat4.0中提供了在JSP和Servelt中直接使用JNDI的方法,下面谈一下在Tomcat4.0中配置和使用JNDI的方法
(以通过JNDI连接数据库为例)
假设使用的数据库是mysql,实验例子在TOMCAT_HOME/webapps/DBTest目录中
A.将mysql的JDBC连接库mm.mysql-2.0.9-bin.jar放入TOMCAT_HOME/common/lib中
B.配置TOMCAT_HOME/conf/serer.xml文件在<Service>;段中加入一个Context:
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
</Context>
这是DBTest的根路径,这是为了在DBTest中使用做准备.
C.在上面加入的<Context>;段加入
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>;factory</name>
<value>;org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>;maxActive</name>
<value>;100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>;maxIdle</name>
<value>;30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>;maxWait</name>
<value>;10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>;username</name>;
<value>;test</value>
</parameter>
<parameter>
<name>;password</name>
<value>;test</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->;
<parameter>;
<name>;driverClassName</name>;
<value>;org.gjt.mm.mysql.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.-->
<parameter>
<name>;url</name>
<value>;jdbc:mysql://localhost:3306/test</value>
</parameter>
</ResourceParams>
这里每一个小段都有英文注解,是Tomcat提供的,我们可以将按照Sample加入,主要修改的是driverClassName,
url,和用户帐号;需要强调的是"jdbc/TestDB"就是JDNI要查找的Name.
在web.xml中加入
<resource-ref>
<description>;DB Connection</description>
<res-ref-name>;jdbc/TestDB</res-ref-name>
<res-type>;javax.sql.DataSource</res-type>
<res-auth>;Container</res-auth>
</resource-ref>
这里的jdbc/TestDb要和C中Resource段的name匹配