本文旨在解釋JavaEE中的ServletContextListener接口及用法。
1.何時(shí)需要使用ServletContextListener?
通常我們可能有這樣的需求:即在web 應(yīng)用啟動(dòng)之前運(yùn)行一些代碼。例如:我們可能需要?jiǎng)?chuàng)建一個(gè)數(shù)據(jù)庫連接以便web應(yīng)用在任何時(shí)候都能使用它執(zhí)行一些操作,并且當(dāng)web應(yīng)用關(guān)閉的時(shí)候能夠關(guān)閉數(shù)據(jù)庫連接。
2.如何實(shí)現(xiàn)這個(gè)需求?
Java EE規(guī)范提供了一個(gè)叫ServletContextListener的接口,這個(gè)接口可以實(shí)現(xiàn)我們的需求。ServletContextListener監(jiān)聽servlet context的生命周期事件。當(dāng)這個(gè)listener關(guān)聯(lián)的web應(yīng)用啟動(dòng)和關(guān)閉的時(shí)候,這個(gè)接口會(huì)收到通知。下面是javadoc對(duì)這個(gè)接口的說明:
Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
如果想要監(jiān)聽web應(yīng)用的啟動(dòng),可以使用contextInitialized(ServletContextEvent event)方法。
Notification that the web application initialization process is starting. All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized.
如果要監(jiān)聽web應(yīng)用的停止(關(guān)閉),用contextDestroyed(ServletCOntextEvent event)方法。
Notification that the servlet context is about to be shut down. All servlets and filters have been destroy()ed before any ServletContextListeners are notified of context destruction.
如下創(chuàng)建一個(gè)監(jiān)聽器類:
package com.cruise;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
System.out.println("context initialized");
}
public void contextDestroyed(ServletContextEvent event) {
System.out.println("context destroyed");
}
}
接下來在web.xml文件中配置listener
</web-app ...>
<listener>
<listener-class>com.thejavageek.MyServletContextListener</listener-class>
</listener>
</web-app>
配置完成后,部署應(yīng)用到tomcat服務(wù)器并啟動(dòng)tomcat,將會(huì)看到如下的日志。
INFO: Starting service Catalina
Oct 24, 2015 10:52:04 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
context initialized
Oct 24, 2015 10:52:04 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Oct 24, 2015 10:52:04 AM org.apache.jk.common.ChannelSocket init
- 繼承thread
public class ThreadListener extends Thread implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
super.start();
}
public void contextDestroyed(ServletContextEvent event) {
super.stop();
}
@override
public void run(){
}
}