Servlet Listener之ServletContextListener用法

本文旨在解释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 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值