1. 修改Tomcat安装目录下的conf文件夹里的context.xml文件.
在context.xml文件中添加以下内容:(注意是在<Context></Context>之间添加)
<Resource name="jdbc/mytest"
auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
driverClassName="com.sql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydatabase" />
其中:name必须为"jdbc/..."的形式."..."是指你想给datasource命名的名字.
username是连接数据库的用户名.
password是连接数据库的密码.
url是jdbc:mysql://主机名:端口号/数据库名称
2. 在Tomcat安装目录下的webapps里创建工程MyTest工程.
3. 将ROOT下的WEB-INF文件夹整个拷贝至MyTest中.
4. 修改修改MyTest\WEB-INF中web.xml,在<web-app></web-app>中添加如下
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mytest</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
此处<res-ref-name>的名字应与context.xml中Resource name一致。
5. 在Tomcat服务器下的lib文件夹下添加连接MySQL数据库的驱动包。
6. MyTest下编写jsp测试连接池是否成功,在MyTest文件夹下创建myTest.jsp文件.输入内容如下:(注意修改数据库名字.)
<%@ page import=”java.sql.*, javax.sql.*, javax.naming.*”contentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<TITLE>连接池测试页面</TITLE>
</HEAD>
<BODY>
<%out.println("<h1>Hello,test DBCP ! </h1>");%>
<%
try {
Context ctx = new InitialContext(); //建立Context对象
DataSource ds = (DataSource) envctx.lookup("java:comp/env/jdbc/mytest"); //建立datasource对象Connection conn=ds.getConnection(); //通过数据源对象建连接
Statement st=conn.createStatement();
String sql="select * from myuser";
ResultSet rs=st.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<br>
<%
}
} catch (Exception e) {
e.printStackTrace();
} %>
<%
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
%>
</BODY>
</HTML>
7. 重启tomcat,访问http://localhost:8080/MyTest/ 输出数据即为成功。