Listener(监听器)

1、Listener(监听器)基本介绍

Filter、Listener和 servlet 是 Java EE 的三大组件。

Listener 监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法立即被执行。

有好几种监听器,其中最常用的是ServletContextListener。除了ServletContextListener外,还有几种Listener:

  • HttpSessionListener:监听HttpSession的创建和销毁事件;
  • ServletRequestListener:监听ServletRequest请求的创建和销毁事件;
  • ServletRequestAttributeListener:监听ServletRequest请求的属性变化事件(即调用ServletRequest.setAttribute()方法);
  • ServletContextAttributeListener:监听ServletContext的属性变化事件(即调用ServletContext.setAttribute()方法);

2、使用ServletContextListener监听器

定义一个ServletContextListener监听器:

@WebListener
public class AppListener implements ServletContextListener {
    // ServletContext对象创建后会调用该方法。一般可在此初始化WebApp,例如打开数据库连接池等:
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext被创建了。。");
    }

    // ServletContext对象销毁之前会调用该方法。一般可在此清理WebApp,例如关闭数据库连接池等:
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext被销毁了。。");
    }
}

上面我们使用了注解 @WebListener 来配置监听器。任何标注为@WebListener,且实现了特定接口的类会被Web服务器自动初始化。

contextInitialized() 方法会在整个Web应用程序初始化完成后执行,contextDestroyed() 方法会在Web应用程序关闭后执行。在启动服务器时,我们可以看到 contextInitialized() 方法会被执行。当正常关闭服务器时,contextDestroyed() 方法会被执行。

2.1、使用 web.xml 配置监听器

除了使用注解配置,我们还可以在 web.xml 里面使用 listener 节点配置监听器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <listener>
        <listener-class>test.Listener01</listener-class>
    </listener>
</web-app>

上面的 listener-class 里面的是监听器的完整类名。

原文地址:https://www.cnblogs.com/wenxuehai/p/14693779.html