Tomcat6.0 配置外部数据源(JNDI)

Tomcat6.0以上版本配置JNDI,只需修改conf下context.xml文件,在Tomcat目录的lib下加入common-dbcp.jar和数据库jar包

<?xml version='1.0' encoding='utf-8'?>
<Context>

<WatchedResource>WEB-INF/web.xml</WatchedResource>

<!-- 新增配置,配置外部数据源 -->
<Resource name="jdbc/DB2source"
auth
="Container"
type
="javax.sql.DataSource"
url
="jdbc:sqlserver://192.168.0.119;DatabaseName=XXXXX"
username
="sa"
password
="XXXXX."
driverClassName
="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxIdle
="3"
maxWait
="-1"
maxActive
="50" />

</Context>

       参数介绍:

       name:给数据源设置名字(jndi) 
       auth:表示数据源由谁管理
       type:类型 
       maxActive:在连接池中最大的激活连接数 
       maxIdle:在连接池中最大的保留(空闲)连接数 
       maxWait:客户端在队列池中最大等待时间(秒) 

测试代码(新建Web工程,无法在Main方法中测试):

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>   
<%@ page language="java"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>配置 JNDI</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
Tomcat6.
0+ 配置 JNDI(common-dbcp.jar,sqljdbc4.jar)
<%
Connection conn
=null;
PreparedStatement ps
=null;
ResultSet rs
=null;
try {
Context ctx
= new InitialContext();

Context envContext
= (Context) ctx.lookup("java:/comp/env");
DataSource ds
= (DataSource) envContext.lookup("jdbc/DB2source");
conn
=ds.getConnection();

if (conn == null) {
System.out.println(
"连接未获取成功...........");
}
else {
System.out.println(
"获取连接............");
}
String sql
= "select * from systemusers";
ps
=conn.prepareStatement(sql);
rs
= ps.executeQuery();
while (rs.next()) {
System.out.println(
"===============Name:"+rs.getString("userName"));
out.println(
"===============Name:"+rs.getString("userName")+"\r");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if(conn!=null){
conn.close();
}
if(ps!=null){
ps.close();
}
if(rs!=null){
rs.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}

}

%>
</body>
</html>

 

 

posted on 2011-09-03 18:38  archie2010  阅读(914)  评论(0编辑  收藏  举报