本文旨在解释JavaEE中的ServletContextListener接口及用法。
1.何时需要使用ServletContextListener?
通常我们可能有这样的需求:即在web 应用启动之前运行一些代码。例如:我们可能需要创建一个数据库连接以便web应用在任何时候都能使用它执行一些操作,并且当web应用关闭的时候能够关闭数据库连接。
2.如何实现这个需求?
Java EE规范提供了一个叫ServletContextListener的接口,这个接口可以实现我们的需求。ServletContextListener监听servlet context的生命周期事件。当这个listener关联的web应用启动和关闭的时候,这个接口会收到通知。下面是javadoc对这个接口的说明:1
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.
如果想要监听web应用的启动,可以使用contextInitialized(ServletContextEvent event)方法。1
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.
如果要监听web应用的停止(关闭),用contextDestroyed(ServletCOntextEvent event)方法。1
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.
如下创建一个监听器类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package 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文件中配置listener1
2
3
4
5</web-app ...>
<listener>
<listener-class>com.thejavageek.MyServletContextListener</listener-class>
</listener>
</web-app>
配置完成后,部署应用到tomcat服务器并启动tomcat,将会看到如下的日志。1
2
3
4
5
6
7INFO: 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
`
java
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(){}
}`