Tomcat中配置和使用JNDI

时间:2022-10-29 19:13:50
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.

D. 在JSPh或servlet中使用JNDI查找服务
下面是在JSP文件中关于JNDI使用的代码(文件名记为UserHandleDB.jsp)
需要注意的是JNDI NAME要在前面加上"java:comp/env/"

<%@ page language="java"%>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>

<%
String jndi_name="java:comp/env/jdbc/TestDB";
String select_user_sql="select userid,name,birthday, email from emp";
String colnames[][]={{"User ID","Name","Birth day","EMail"},
{"userid","name","birthday","email"}};
Vector userSet=new Vector();
Vector columnSet=new Vector();

for(int i=0;i<colnames[0].length;i++){
columnSet.add(colnames[0][i]);
}
userSet.add(columnSet);

Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("No Context");

DataSource ds = (DataSource)ctx.lookup(jndi_name);

Connection conn = ds.getConnection();

try {
PreparedStatement psPreparedStatement=conn.prepareStatement(select_user_sql);
ResultSet resultSet = psPreparedStatement.executeQuery();
while(resultSet.next()){
columnSet=new Vector();
for(int i=0;i<colnames[1].length;i++){
columnSet.add(resultSet.getString(colnames[1][i]));
}
userSet.add(columnSet);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
conn.close();
%>


E. 引用UserHandleDB.jsp(记为ViewTable.jsp)
<html>
<head>
<title>Test Database </title>
<body >
<%@ include file="UserHandleDB.jsp" %>
<table border="1" >
<%
for(int i=0;i<userSet.size();i++){
Vector colSet=(Vector)userSet.get(i);
out.print("<tr>");
for(int j=0;j<colSet.size();j++){
String col=(String)colSet.get(j);
out.print("<td>"+col+"</td>");
}
out.print("</tr>");
}
%>
</table>
</body>
</html>

F. 在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匹配

G. 观察结果
首先确定数据库已经启动,接着启动Tomcat,如果Tomcat启动异常,可能的原因是数据库的JDBC库没有加载
最后打开浏览器,访问
http://localhost:8080/DBTest/ViewTa...涂梢钥吹浇峁?/a>