The operating environment and resources used by this routine:
1. Tomcat 5.5
2. Mysql 4.1
3. mysql JDBC driver: 3.1.13
(The above procedures can be downloaded directly to the relevant official website)
Step1: First create a listener servlet, which is used to initialize the shared resource, which is used primarily to create the data source in the application, placing the class in the web-inf/classes/kinglong/jmediasoft/servlets/directory, The code is as follows:
/** */ /**
* @ (#) Resourcemanagerlistener.java
*
* Resource Initialization listener
*
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 ("Cannot create data source:" + e.getmessage ());
return;
}
Application.setattribute ("DataSource", DS);//Place data source variable in application scope
}
public void contextdestroyed (Servletcontextevent sce) {
ServletContext application = Sce.getservletcontext ();
Application.removeattribute ("DataSource");
ds = NULL;
}
}
Step2: Configure the Web.xml related code as follows:
< 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: Set up a test page and test the page code as follows:
< 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: Restart Tomcat application, use http://localhost:8080/test/test.jsp link to execute this page, my output is as follows. This is the only record in my comicinfo table. The bold is the field of the table, followed by the corresponding field value.