在TOMCAT中简单配置DBCP数据库连接池

本文介绍如何在Tomcat中配置DBCP连接池,并通过示例展示了具体的XML配置方法及JSP测试页面代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    连接池是用来获取一组数据库连接的东东,在TOMCAT中提供了名叫:DBCP的连接池,而要想学习连接池的使用,需要先对其进行配置,之后连接测试。以下阐述了学习配置的过程。

    简单配置方法:

    找到TOMCAT安装目录中的conf/server.xml,在<Host></Host>之间原来有这一行语句:

<Context path="/HelloWorld" reloadable="true" docBase="D:/F/Learn/HelloWorld" workDir="D:/F/Learn/HelloWorld/work" />

这是我工程目录的部署信息,修改它如下:

<Context path="/HelloWorld" reloadable="true" docBase="D:/F/Learn/HelloWorld" workDir="D:/F/Learn/HelloWorld/work">
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
maxActive="30"
maxIdle="10"
maxWait="10000"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/test"/>
</Context>

其中我的数据库为test,同时在我的ECLIPSE中HelloWorld工程的WEB-INF/web.xml中添加如下语句:

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

这段放在<web-app></web-app>中

重启TOMCAT,如果不报错,则可写一JSP页面测试:

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ 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>数据库连接池DBCP</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">
    
    
<!--
    
<link rel="stylesheet" type="text/css" href="styles.css">
    
-->
  
</head>
  
  
<body>
<% 

Context initCtx 
= new InitialContext(); 
Context ctx 
= (Context) initCtx.lookup("java:comp/env");
DataSource ds 
= (DataSource) ctx.lookup("jdbc/test"); 
for(int i=0;i<40;i++)
{
Connection conn 
= ds.getConnection();
out.print(
"创建连接成功"+i+"<br>");
try{
conn.close();
out.print(
"关闭连接成功"+i+"<br>");
}
catch(Exception e)
{
e.printStackTrace();
}

}

out.print(
"配置成功");
%>
  
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值