本文介绍如果利用监听器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 = " " %>
<% @ taglib prefix = " sql " uri = " " %>
<% @ taglib prefix = " fn " uri = " " %>
<!-- 执行数据库查询操作,将查询结果保存到变量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应用,用的链接来执行此页面,我的输出如下。这是我的comicinfo表中的唯一一条记录。黑体是表的字段,后面是对应的字段值。