Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-01 13:55:55
Original
1120 people have browsed it

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

  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相关代码,代码如下:


jdbcURL 
jdbc:mysql://localhost:3306/comic 

user 
root 

password 
root 


kinglong.jmediasoft.servlets.ResourceManagerListener

  step3:建立测试页面,测试页面代码如下:
sql ="SELECT * FROM comicinfo"  /> 



数据库测试页面 





$ { fn:escapeXml(column.key)}: 
$ { fn:escapeXml(column.value)}

  step4:重新启动Tomcat应用,用http://localhost:8080/test/test.jsp的链接来执行此页面,我的输出如下。这是我的comicinfo表中的唯一一条记录。黑体是表的字段,后面是对应的字段值。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template