TOMCAT下的JNDI的配置

时间:2022-06-04 00:42:13

一、第一种配置局部JNDI

1、在tomcat的conf目录下的server.xml的<host>标签内,添加:

<Context path="/TestMvcMode"
docBase="TestMvcMode" reloadable="true"
debug="8">
<Resource name="jdbc/test"
auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="root" password="123"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"/>
</Context>

2、在web.xml中配置如下代码(也可以不用配置,resource-ref元素用于指定对外部资源的servlet引用的声明)

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

3、在jsp中调用加载jndi方式,不可以直接用main方法测试,必须通过启动容器从jsp中调用:

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>测试Tomcat数据源</title>
</head>
<body>
<%
//初始化Context,使用InitialContext初始化Context
Context ctx=new InitialContext();
/*
通过JNDI查找数据源,该JNDI为java:comp/env/jdbc/dstest,分成两个部分
java:comp/env是Tomcat固定的,Tomcat提供的JNDI绑定都必须加该前缀
jdbc/dstest是定义数据源时的数据源名
*/
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/test");
//获取数据库连接
Connection conn=ds.getConnection();
//获取Statement
Statement stmt=conn.createStatement();
//执行查询,返回ResulteSet对象
ResultSet rs=stmt.executeQuery("select * from userinfo");
while(rs.next())
{
out.println(rs.getInt(1)
+ "\t" + rs.getString(2) + "<br/>");
}
%>
</body>
</html>

二、第二种配置全局JNDI

     1、在tomcat的conf文件夹下的context.xml配置文件中加入:

<Resource name="jdbc/test" 
auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="root" password="123" 
driverClassName="com.mysql.jdbc.Driver" 
url="jdbc:mysql://localhost:3306/test"/> 

后续其他配置同第一种方式。

三、不依赖于tomcat的局部配置方式

1、在项目的META-INFO下面新建context.xml。加入如下:

<?xml version="1.0" encoding="UTF-8"?>  

<Context path="/TestMvcMode" 
docBase="TestMvcMode" reloadable="true" 
debug="8"> 
<Resource name="jdbc/test" 
auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="root" password="123" 
driverClassName="com.mysql.jdbc.Driver" 
url="jdbc:mysql://localhost:3306/test"/> 
</Context>

其他配置同第一种方式。

参考:http://blog.csdn.net/lgm277531070/article/details/6711177