Home > Database > Mysql Tutorial > Jsp连接Mysql数据库:利用Servlet监听器

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

WBOY
Release: 2016-06-07 16:05:57
Original
1700 people have browsed it

本例程所使用的运行环境及资源: 1. Tomcat 5.5 2. Mysql 4.1 3. mysql jdbc驱动:3.1.13 (以上程序可以直接到相关官方网站下载到) step1: 首先创建一个监听器servlet,这个监听器用来初始化共享资源,本例中主要用来在应用中创建数据源,把这个类置于WEB-I

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

1. Tomcat 5.5                                   
2. Mysql 4.1
3.  mysql jdbc驱动:3.1.13

(以上程序可以直接到相关官方网站下载到)

step1:首先创建一个监听器servlet,这个监听器用来初始化共享资源,本例中主要用来在应用中创建数据源,把这个类置于WEB-INF/classes/kinglong/jmediasoft/servlets/目录下,代码如下:

<p>/** */ /** <br>* @(#)ResourceManagerListener.java<br>*<br>* 资源初始化监听器<br>*<br>package  kinglong.jmediasoft.servlets;</p><p>import  javax.servlet. * ;<br>import  javax.servlet.http. * ;<br>import  com.mysql.jdbc.jdbc2.optional. * ;</p><p>public   class  ResourceManagerListener  implements  ServletContextListener  { <br>private  DataSource ds = null ; <br>public   void  contextInitialized(ServletContextEvent sce)  {<br>ServletContext application = sce.getServletContext();<br>String jdbcurl = application.getInitParameter( " jdbcURL " );<br>String user = application.getInitParameter( " user " );<br>String password = application.getInitParameter( " password " );<br>try  {<br>ds = new  MysqlConnectionPoolDataSource();<br>ds.setUrl(jdbcurl);<br>ds.setUser(user);<br>ds.setPassword(password);<br>} catch (Exception e)  {<br>application.log( " 无法创建数据源: " + e.getMessage()); <br>return ;  <br>}   <br>application.setAttribute( " dataSource " ,ds);//将数据源变量置于应用作用域中<br>} <br><br>public   void  contextDestroyed(ServletContextEvent sce)  {<br>ServletContext application = sce.getServletContext();<br>application.removeAttribute( " dataSource " );<br>ds = null ;<br>} <br>} </p>
Copy after login

step2:配置web.xml相关代码,代码如下:

<p> <br> jdbcURL  param-name> <br> jdbc:mysql://localhost:3306/comic  param-value>  context-param> <br> <br> user  param-name> <br> root  param-value> <br> <br> password  param-name> <br> root  param-value> <br> <br> </p><p>kinglong.jmediasoft.servlets.ResourceManagerListener</p>
Copy after login
 
step3:建立测试页面,测试页面代码如下:

<p></p><p>sql ="SELECT * FROM comicinfo"   />  </p><p> <br> <br> <br> 数据库测试页面  title=""> </p><p> </p><p> <br> <br> <br> <br> $ { fn:escapeXml(column.key)}:  b> td> <br> $ { fn:escapeXml(column.value)} </p>
Copy after login

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

(责任编辑 火凤凰 sunsj@51cto.com  TEL:(010)68476636-8007)


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