本文介紹如果利用監聽器servlet來設置mysql應用數據源。 本例程所使用的運行環境及資源:
1. Tomcat 5.5
2. Mysql 4.1
3. mysql jdbc驅動:3.1.13
(以上程序可以直接到相關官方網站下載到)
step1:
首先創建一個監聽器servlet,這個監聽器用來初始化共享資源,本例中主要用來在應用中創建數據源,把這個類置於WEB-INF/classes/kinglong/jmediasoft/servlets/目錄下,代碼如下:
/** */ /**
* @(#)ResourceManagerListener.java
*
* 資源初始化監聽器
*
* @author ekinglong
* @version 1.00 2006/10/5
*/
package kinglong.jmediasoft.servlets;
import javax.servlet. * ;
import javax.servlet.http. * ;
import com.mysql.jdbc.jdbc2.optional. * ;
public class ResourceManagerListener implements ServletContextListener {
private DataSource ds = null ;
public void contextInitialized(ServletContextEvent sce) {
ServletContext application = sce.getServletContext();
String jdbcurl = application.getInitParameter( " jdbcURL " );
String user = application.getInitParameter( " user " );
String password = application.getInitParameter( " password " );
try {
ds = new MysqlConnectionPoolDataSource();
ds.setUrl(jdbcurl);
ds.setUser(user);
ds.setPassword(password);
} catch (Exception e) {
application.log( " 無法創建數據源: " + e.getMessage());
return ;
}
application.setAttribute( " dataSource " ,ds);//將數據源變量置於應用作用域中
}
public void contextDestroyed(ServletContextEvent sce) {
ServletContext application = sce.getServletContext();
application.removeAttribute( " dataSource " );
ds = null ;
}
}
step2:配置web.xml相關代碼,代碼如下:
< context-param >
< param-name > jdbcURL </ param-name >
< param-value > jdbc:mysql://localhost:3306/comic </ param-value >
</ context-param >
< context-param >
< param-name > user </ param-name >
< param-value > root </ param-value >
</ context-param >
< context-param >
< param-name > password </ param-name >
< param-value > root </ param-value >
</ context-param >
< listener >
< listener-class > kinglong.jmediasoft.servlets.ResourceManagerListener </ listener-class >
</ listener >
step3:建立測試頁面,測試頁面代碼如下:
<% @ page contentType = " text/html; charset=gb2312 " language = " java " import = " java.sql.* " errorPage = "" %>
<% @ taglib prefix = " c " uri = " http://java.sun.com/jsp/jstl/core " %>
<% @ taglib prefix = " sql " uri = " http://java.sun.com/jsp/jstl/sql " %>
<% @ taglib prefix = " fn " uri = " http://java.sun.com/jsp/jstl/functions " %>
<!-- 執行數據庫查詢操作,將查詢結果保存到變量comicinfo中 -->
< sql:query var ="comicinfo" dataSource ="$ { dataSource}" sql ="SELECT * FROM comicinfo" />
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=gb2312" >
< title > 數據庫測試頁面 </ title >
</ head >
< body >
<!-- 下面是將數據庫中的每條記錄以表的"字段名:字段值"的形式打印出來 -->
< table >
< c:forEach items ="$ { comicinfo.rows}" var ="row" >
< c:forEach items ="$ { row}" var ="column" >
< tr >
< td align ="right" >< b > $ { fn:escapeXml(column.key)}: </ b ></ td >
< td align ="left" > $ { fn:escapeXml(column.value)} </ td >
</ tr >
</ c:forEach >
</ c:forEach >
</ table >
</ body >
</ html >
step4:重新啟動Tomcat應用,用http://localhost:8080/test/test.jsp的鏈接來執行此頁面,我的輸出如下。這是我的comicinfo表中的唯一一條記錄。黑體是表的字段,後面是對應的字段值。