標籤:
使用Listener步驟
1. 定義Listener實作類別
2. 在web.xml中配置(或使用Annotation)
使用C3P0方式建立資料庫連接池需要添加的jar包
1.c3p0-0.9.5.jar
2.c3p0-oracle-thin-extras-0.9.5.jar
3.mchange-commons-java-0.2.9.jar
1 package cn.sdut.lah.listener; 2 3 import java.sql.Connection; 4 import javax.servlet.ServletContext; 5 import javax.servlet.ServletContextEvent; 6 import javax.servlet.ServletContextListener; 7 8 import com.mchange.v2.c3p0.ComboPooledDataSource; 9 10 11 public class GetConnListener implements ServletContextListener {12 13 //啟動web應用時,該方法被調用14 @Override15 public void contextInitialized(ServletContextEvent sce) {16 try {17 // 取得應用的ServletContext執行個體18 ServletContext application = sce.getServletContext();19 20 // 從配置參數中擷取驅動21 String driver = application.getInitParameter("driver");22 // 從配置參數中擷取資料庫url23 String url = application.getInitParameter("url");24 // 從配置參數中擷取使用者名稱25 String user = application.getInitParameter("user");26 // 從配置參數中擷取密碼27 String password = application.getInitParameter("pass");28 29 // 建立串連池執行個體30 ComboPooledDataSource cpds = new ComboPooledDataSource();31 // 設定串連池串連資料庫所需要的驅動32 cpds.setDriverClass(driver);33 // 設定串連資料庫所需的驅動34 cpds.setJdbcUrl(url);35 // 設定串連資料庫的使用者名稱36 cpds.setUser(user);37 // 設定串連資料庫的密碼38 cpds.setPassword(password);39 // 設定串連池的最大串連數40 cpds.setMaxPoolSize(40);41 // 設定串連池的最小串連數42 cpds.setMinPoolSize(2);43 // 設定串連池的初始串連數44 cpds.setInitialPoolSize(10);45 // 設定串連池的緩衝statement最大數46 cpds.setMaxStatements(180);47 48 // 將DataSource設定為application範圍內的屬性49 application.setAttribute("ds", cpds);50 51 } catch (Exception e) {52 e.printStackTrace();53 }54 55 }56 57 //關閉web應用58 @Override59 public void contextDestroyed(ServletContextEvent sce) {60 ServletContext application = sce.getServletContext();61 ComboPooledDataSource ds = (ComboPooledDataSource) application62 .getAttribute("ds");63 try {64 Connection conn = ds.getConnection();65 if (conn != null) {66 conn.close();67 }68 } catch (Exception e) {69 e.printStackTrace();70 }71 72 }73 74 }
在web.xml中配置參數
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 6 7 <context-param> 8 <param-name>driver</param-name> 9 <param-value>com.mysql.jdbc.Driver</param-value>10 </context-param>11 12 <context-param>13 <param-name>url</param-name>14 <param-value>jdbc:mysql://localhost:3306/javaee</param-value>15 </context-param>16 17 <context-param>18 <param-name>user</param-name>19 <param-value>root</param-value>20 </context-param>21 22 <context-param>23 <param-name>pass</param-name>24 <param-value>ab123456</param-value>25 </context-param>36 37 <listener>38 <listener-class>cn.sdut.lah.listener.GetConnListener</listener-class>39 </listener> 40 41 </web-app>
通過實現ServletContextListener介面建立資料庫連接池(C3P0方式)