當(dāng)Web應(yīng)用程序部署在服務(wù)器上時(shí),會(huì)通知ServletContextEvent事件。
如果要在部署Web應(yīng)用程序時(shí)執(zhí)行某些操作,例如創(chuàng)建數(shù)據(jù)庫連接,創(chuàng)建項(xiàng)目的所有表等,則需要實(shí)現(xiàn)ServletContextListener接口并提供其方法的實(shí)現(xiàn)。
ServletContextEvent類的構(gòu)造方法
在ServletContextEvent類中只定義了一個(gè)構(gòu)造函數(shù)。Web容器在ServletContext實(shí)例之后創(chuàng)建ServletContextEvent的實(shí)例。
ServletContextEvent(ServletContext e)ServletContextEvent類的方法
ServletContextEvent類中只定義了一個(gè)方法:
public ServletContext getServletContext() - 返回ServletContext的實(shí)例。ServletContextListener接口的方法
在ServletContextListener接口中聲明了兩種方法,這些方法必須由servlet程序員實(shí)現(xiàn),以執(zhí)行一些操作,如創(chuàng)建數(shù)據(jù)庫連接等。
public void contextInitialized(ServletContextEvent e): 當(dāng)應(yīng)用程序部署在服務(wù)器上時(shí)被調(diào)用。public void contextDestroyed(ServletContextEvent e): 當(dāng)應(yīng)用程序從服務(wù)器取消部署時(shí)被調(diào)用。在這個(gè)例子中,從employees表中檢索數(shù)據(jù)。為了實(shí)現(xiàn)這個(gè)服務(wù),我們在監(jiān)聽器類中創(chuàng)建了連接數(shù)據(jù)庫對(duì)象,并在servlet中使用了連接對(duì)象。
首先,在MySQL中創(chuàng)建一個(gè)名稱為:testdb 的數(shù)據(jù)庫,創(chuàng)建以下表及以數(shù)據(jù)記錄 -
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', '??谑腥嗣翊蟮?800號(hào)', '8900.00');
INSERT INTO `employees` VALUES ('2', '張輝', '28', '廣州天河區(qū)珠村市場', '15800.00');
INSERT INTO `employees` VALUES ('3', '林賢弟', '25', '廣州白云區(qū)龍?zhí)链?20號(hào)', '18990.00');
打開Eclipse,創(chuàng)建一個(gè)動(dòng)態(tài)Web項(xiàng)目:ServletContextEvent,其完整的目錄結(jié)構(gòu)如下 -

以下是項(xiàng)目中的幾個(gè)主要的文件代碼。
文件:index.html -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ServletContextListener實(shí)例</title>
</head>
<body style="text-algin: center;">
<a href="getdata">點(diǎn)擊讀取employees表中的數(shù)據(jù)</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("獲取數(shù)據(jù)庫連接異常~!");
}
// 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應(yīng)用程序(在項(xiàng)目名稱上點(diǎn)擊右鍵->”Run On Server…”),打開瀏覽器訪問URL: http://localhost:8080/ServletContextEvent/ ,如果沒有錯(cuò)誤,應(yīng)該會(huì)看到以下結(jié)果 -

點(diǎn)擊上面鏈接后,從數(shù)據(jù)庫表中讀取到的數(shù)據(jù)如下所示 -

在這個(gè)例子中,我們創(chuàng)建一個(gè)項(xiàng)目所使用的表。因此不需要在數(shù)據(jù)庫中手動(dòng)創(chuàng)建所有表。
修改上面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的其他示例