连接池是用来获取一组数据库连接的东东,在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 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 >