1、配置Tomcat。將需要使用的JDBC驅動jar包複製在Tomcat目錄下lib文件夾下,本例使用mysql-connector-java-5.0.0.jar
2、配置context.xml文件。打開Tomcat目錄下conf文件夾下的context.xml文件,
將下面代碼添加到Context標籤內
<Resource name=”jdbc/mysql”
auth=”Container”
type=”javax.sql.DataSource”
driverClassName=”com.mysql.jdbc.Driver”
url=”jdbc:mysql://localhost:3306/test”
username=”你的數據庫用戶名”
password=”你的密碼”
maxActive=”100″
maxIdle=”30″
maxWait=”10000″
/>
3、配置web應用WEB-INF\web.xml
下面打開web.xml文件,在其根節點下添加數據源的引用設置。
<resource-ref>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4、配置完成後我們就可以在Java代碼中訪問使用連接池了,新建index.jsp驗證
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.DataSource"%>
<%@ page import="javax.naming.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</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>
use the jdbc data resource<br>
<%
Connection con = null;
Statement stat = null;
ResultSet rs =null;
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
con = ds.getConnection();
stat = con.createStatement();
String sql = "select * from user";
rs = stat.executeQuery(sql);
while(rs.next()) {
out.println("<li>帳號: "+ rs.getString(2).trim());
out.println("密碼: " + rs.getString(3).trim()+"</li>");
}
rs.close();
stat.close();
con.close();
%>
</body>
</html>