当Web应用程序部署在服务器上时,会通知ServletContextEvent
事件。
如果要在部署Web应用程序时执行某些操作,例如创建数据库连接,创建项目的所有表等,则需要实现ServletContextListener
接口并提供其方法的实现。
ServletContextEvent类的构造方法
在ServletContextEvent
类中只定义了一个构造函数。Web容器在ServletContext
实例之后创建ServletContextEvent
的实例。
ServletContextEvent(ServletContext e)
ServletContextEvent类的方法
ServletContextEvent
类中只定义了一个方法:
public ServletContext getServletContext()
- 返回ServletContext
的实例。
ServletContextListener接口的方法
在ServletContextListener
接口中声明了两种方法,这些方法必须由servlet
程序员实现,以执行一些操作,如创建数据库连接等。
public void contextInitialized(ServletContextEvent e)
: 当应用程序部署在服务器上时被调用。public void contextDestroyed(ServletContextEvent e)
: 当应用程序从服务器取消部署时被调用。
ServletContextEvent和ServletContextListener的示例
在这个例子中,从employees
表中检索数据。为了实现这个服务,我们在监听器类中创建了连接数据库对象,并在servlet中使用了连接对象。
首先,在MySQL中创建一个名称为:testdb 的数据库,创建以下表及以数据记录 -
DROP TABLE IF EXISTS `employees`;
CREATE TABLE `employees` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL DEFAULT '',
`age` int(3) unsigned NOT NULL DEFAULT '0',
`address` varchar(254) DEFAULT NULL,
`salary` float(8,2) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of employees
-- ----------------------------
INSERT INTO `employees` VALUES ('1', '李小春', '23', '海口市人民大道1800号', '8900.00');
INSERT INTO `employees` VALUES ('2', '张辉', '28', '广州天河区珠村市场', '15800.00');
INSERT INTO `employees` VALUES ('3', '林贤弟', '25', '广州白云区龙塘村120号', '18990.00');
打开Eclipse,创建一个动态Web项目:ServletContextEvent,其完整的目录结构如下 -
以下是项目中的几个主要的文件代码。
文件:index.html -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ServletContextListener实例</title>
</head>
<body style="text-algin: center;">
<a href="getdata">点击读取employees表中的数据</a>
</body>
</html>
文件:MyListener.java -
package com.yiibai;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* Application Lifecycle Listener implementation class MyListener
*
*/
@WebListener
public class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql://localhost/testdb";
// Database credentials
String dbUser = "root";
final String passwd = "123456";
try {
Class.forName(jdbcDriver);
Connection con = DriverManager.getConnection(dbURL, dbUser, passwd);
// storing connection object as an attribute in ServletContext
ServletContext ctx = event.getServletContext();
ctx.setAttribute("mycon", con);
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Servlet has contextDestroyed...");
}
}
文件:FetchData.java -
package com.yiibai;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FetchData
*/
public class FetchData extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Retrieving connection object from ServletContext object
ServletContext ctx = getServletContext();
Connection con = (Connection) ctx.getAttribute("mycon");
if(con==null) {
System.out.println("获取数据库连接异常~!");
}
// retieving data from emp32 table
String sql = "SELECT * FROM employees";
PreparedStatement ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
out.print("<br>" + rs.getString(1) + " " + rs.getString(2));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
}
文件:web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>ServletContextEvent</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.yiibai.MyListener</listener-class>
</listener>
<servlet>
<servlet-name>FetchDataServlet</servlet-name>
<servlet-class>com.yiibai.FetchData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchDataServlet</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>
在编写上面代码后,部署此Web应用程序(在项目名称上点击右键->”Run On Server…”),打开浏览器访问URL: http://localhost:8080/ServletContextEvent/ ,如果没有错误,应该会看到以下结果 -
点击上面链接后,从数据库表中读取到的数据如下所示 -
ServletContextListener创建项目表的示例
在这个例子中,我们创建一个项目所使用的表。因此不需要在数据库中手动创建所有表。
修改上面MyListener.java中的示例代码:
package com.yiibai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* Application Lifecycle Listener implementation class MyListener
*
*/
@WebListener
public class MyListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql://localhost/testdb";
// Database credentials
String dbUser = "root";
final String passwd = "123456";
try {
Class.forName(jdbcDriver);
Connection con = DriverManager.getConnection(dbURL, dbUser, passwd);
String query="CREATE TABLE `employees` (" +
" `id` int(10) unsigned NOT NULL AUTO_INCREMENT," +
" `name` varchar(64) NOT NULL DEFAULT ''," +
" `age` int(3) unsigned NOT NULL DEFAULT '0'," +
" `address` varchar(254) DEFAULT NULL," +
" `salary` float(8,2) unsigned DEFAULT NULL," +
" PRIMARY KEY (`id`)" +
") ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;";
PreparedStatement ps=con.prepareStatement(query);
ps.executeUpdate();
System.out.println(query);
// storing connection object as an attribute in ServletContext
ServletContext ctx = event.getServletContext();
ctx.setAttribute("mycon", con);
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Servlet has contextDestroyed...");
}
}
ServletContextListener的其他示例