位置:海鸟网 > IT > mySQL >

Jsp连接Mysql数据库:利用Servlet监听器

本例程所使用的运行环境及资源:

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应用,用:8080/test/test.jsp的链接来执行此页面,我的输出如下。这是我的comicinfo表中的唯一一条记录。黑体是表的字段,后面是对应的字段值。