2008-06-16 11:02:20
在tomcat中配置连接池需要注意tomcat6.0与6.0以下配置的不同,以下均以oracle数据库为例
tomcat5.0配置,在server.xml中添加如下部分
<Context path="" docBase="." debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/OracleDB" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/OracleDB">
<parameter> <name>factory</name> <value>org.apache.commons.dbcp.BasicDataSourceFactory</value> </parameter>
<parameter> <name>driverClassName</name> <value>oracle.jdbc.driver.OracleDriver</value> </parameter>
<parameter> <name>url</name> <value>jdbc:oracle:thin:@127.0.0.1:1521:test</value> </parameter>
<parameter> <name>username</name> <value>test</value> </parameter>
<parameter> <name>password</name> <value>test</value> </parameter>
<parameter> <name>maxActive</name> <value>100</value> </parameter>
<parameter> <name>maxIdle</name> <value>1</value> </parameter>
<parameter> <name>maxWait</name> <value>5000</value> </parameter>
<parameter> <name>removeAbandoned</name><value>true</value> </parameter>
<parameter> <name>logAbandoned</name><value>true</value> </parameter>
<parameter> <name>removeAbandonedTimeout</name> <value>60</value> </parameter>
</ResourceParams>
</Context>
而在6.0中,要在server.xml中添加:
<Context path="/PdaManage" docBase="d:/pda/PdaManage" debug="5" reloadable="true" crossContext="true">
<Resource
name="jdbc/OracleDB"
type="javax.sql.DataSource"
password="test"
driverClassName="oracle.jdbc.driver.OracleDriver"
maxIdle="5"
maxWait="5000"
username="test"
url="jdbc:oracle:thin:@127.0.0.1:test"
maxActive="10"/>
</Context>
其中path是你项目访问的根目录,docbase是你部署项目的路径地址
要使用jndi的话还需要在web.xml中添加:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/OracleDB</res-ref-name>
<res-type>javax.sql.DataSource </res-type>
<res-auth>Container </res-auth>
</resource-ref>
最后需要说明的是tomcat6.0以下的jdbcdriver是存放到common/lib下的,而6.0是放在lib下的,把jdbcdriver考到相应目录下就可以使用了。
以下是测试代码:
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import= "java.sql.* "%>
<%@ page import= "javax.naming.* "%>
<%
try{
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
//获取连接池对象
Object obj = (Object) ctx.lookup("jdbc/OracleDB");
//类型转换
javax.sql.DataSource ds = (javax.sql.DataSource)obj;
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
String strSql = " select * from user";
ResultSet rs = stmt.executeQuery(strSql);
if(rs.next()){
out.println(rs.getString(1));
out.println(rs.getString(2));
out.println(rs.getString(3));
}
}catch(Exception ex){
ex.printStackTrace();
throw new SQLException("cannot get Connection pool.");
}
%>