本例程所使用的運行環境及資源:
1. Tomcat 5.5
2. MySQL 4.1
3. MySQL jdbc驅動:3.1.13
(以上程序可以直接到相關官方網站下載到)
step1:首先創建一個監聽器servlet,這個監聽器用來初始化共享資源,本例中主要用來在應用中創建數據源,把這個類置於WEB-INF/classes/kinglong/jmediasoft/servlets/目錄下,代碼如下:
/** */ /**
* @(#)ResourceManagerListener.Java
*
* 資源初始化監聽器
*
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-value > jdbc:MySQL://localhost:3306/comic
< context-param >
< param-name > user
< param-value > root
< context-param >
< param-name > passWord
< param-value > root
< listener >
< listener-class >
kinglong.jmediasoft.servlets.ResourceManagerListener
step3:建立測試頁面,測試頁面代碼如下:
< sql:query var ="comicinfo" dataSource ="$ { dataSource}"
sql ="SELECT * FROM comicinfo" />
< Html >
< head >
< meta http-equiv ="Content-Type" content ="text/Html; charset=gb2312" >
< title > 數據庫測試頁面
< body >
< table >
< c:forEach items ="$ { comicinfo.rows}" var ="row" >
< c:forEach items ="$ { row}" var ="column" >
< tr >
< td align ="right" >< b > $ { fn:escapeXML(column.key)}:
< td align ="left" > $ { fn:escapeXML(column.value)}
step4:重新啟動Tomcat應用,用http://localhost:8080/test/test.JSP的鏈接來執行此頁面,我的輸出如下。這是我的comicinfo表中的唯一一條記錄。黑體是表的字段,後面是對應的字段值。