载入驱动

注意:要将驱动载入到tomcatlib目录下,

②在该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 阅读(364) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: