Servlet Listener之ServletContextListener用法

来源:互联网 发布:无法安装sql server 编辑:程序博客网 时间:2024/05/22 03:05

本文旨在解释JavaEE中的ServletContextListener接口及用法。
1.何时需要使用ServletContextListener?
通常我们可能有这样的需求:即在web 应用启动之前运行一些代码。例如:我们可能需要创建一个数据库连接以便web应用在任何时候都能使用它执行一些操作,并且当web应用关闭的时候能够关闭数据库连接。
2.如何实现这个需求?
Java EE规范提供了一个叫ServletContextListener的接口,这个接口可以实现我们的需求。ServletContextListener监听servlet context的生命周期事件。当这个listener关联的web应用启动和关闭的时候,这个接口会收到通知。下面是javadoc对这个接口的说明:

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)方法。

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)方法。

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.

如下创建一个监听器类:

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>

配置完成后,部署应用到tomcat服务器并启动tomcat,将会看到如下的日志。

INFO: Starting service CatalinaOct 24, 2015 10:52:04 AM org.apache.catalina.core.StandardEngine startINFO: Starting Servlet Engine: Apache Tomcat/6.0.35context initializedOct 24, 2015 10:52:04 AM org.apache.coyote.http11.Http11Protocol startINFO: Starting Coyote HTTP/1.1 on http-8080Oct 24, 2015 10:52:04 AM org.apache.jk.common.ChannelSocket init
0 0
原创粉丝点击