①載入驅動
注意:要將驅動載入到tomcat的lib目錄下,
②在該web工程中修改該工程的web.xml文件
增加resource-ref結點
1
2 <!-- datasource -->
3 <resource-ref>
4 <description>MySql Datasource example</description>
5 <res-ref-name>jdbc/mysqlEmailPoolTest</res-ref-name>
6 <res-type>javax.sql.DataSource</res-type>
7 <res-auth>Container</res-auth>
8 </resource-ref>
9
10
完整web.xml文件:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6
7 <!-- 首頁 -->
8 <welcome-file-list>
9 <welcome-file>/web/page/index.jsp</welcome-file>
10 </welcome-file-list>
11
12 <!-- datasource -->
13 <resource-ref>
14 <description>MySql Datasource example</description>
15 <res-ref-name>jdbc/mysqlEmailPoolTest</res-ref-name>
16 <res-type>javax.sql.DataSource</res-type>
17 <res-auth>Container</res-auth>
18 </resource-ref>
19
20
21 </web-app>
22
③修改tomcat conf目錄下的server.xml文件
將該工程的結點打開
修改為:
<Context path="/webDBConnPool" reloadable="true" docBase="D:"workspace"webDBConnPool" workDir="D:"workspace"webDBConnPool"work" >
<Resource name="jdbc/mysqlEmailPoolTest" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="1234" driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://127.0.0.1/test"/>
</Context>
④指定數據源:
1 package com.linying.util;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5
6 import javax.naming.InitialContext;
7 import javax.sql.DataSource;
8
9 public class DBConnPool{
10 // private static Logger logger = Logger.getLogger(DBConnPool.class);
11
12 /**
13 * 從Tomcat連接池中取得連接,記得要關閉
14 */
15 public static Connection getConnection() throws SQLException{
16 // 上下文對象
17 InitialContext ctx;
18
19 // 數據源對象
20 DataSource ds;
21
22 try {
23 ctx = new InitialContext();
24 ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysqlEmailPoolTest");
25 return ds.getConnection();
26 } catch (Exception e){
27 e.printStackTrace();
28 //logger.fatal("數據源初始化失敗.原因是"+e.getMessage());
29 throw new SQLException("數據源初始化失敗.原因是"+e.getMessage());
30 }
31 }
32 }
33
注意:
紅色加粗,黃底的(mysqlEmailPoolTest)三處名字自擬但要保證一致
posted on 2010-02-01 19:55
Ying-er 閱讀(373)
評論(0) 編輯 收藏