为了在 Servlet/JSP 应用程序中使用事件驱动编程(Event-Driven Programming),Servlet/JSP 提供了一套监听器的接口和类。

简单的说,监听器就是能够在某种操作发生时,检测到这种操作的发生,并且执行一定动作的操作。

Servlet/JSP 应用提供以下两种方式来创建一个监听器:

  1. 使用WebListener注解 (简单易用,直接实现对应的 Listener 接口即可):

     @WebListener
     public class _ListenerClass_ implements _ListenerInterface_ {
     }      
    
  2. 在配置文件中配置listener元素:

    <lisenter>
        <listener-class>_fully-qualified listener class_</listener-class>
    </lisenter>
    

常见的监听器以及他们所监听的事件:

I. Servlet Context 监听器:

  1. ServletContextListener:监听 ServletContext 初始化或者销毁操作

    • ServletContext 初始化时:
      void contextInitialized (ServletContextEvent event);
    • ServletContext 销毁时:
      void contextDestroyed (ServletContextEvent event);
  2. ServletContextAttributeListener:监听 ServletContext 的属性的添加、删除或者替换

    • ServletContext 属性添加时:
      void attributeAdded (ServletContextAttributeEvent event);
    • ServletContext 属性删除时:
      void attributeRemoved (ServletContextAttributeEvent event);
    • ServletContext 属性替换时:
      void attributeReplaced (ServletContextAttributeEvent event);

II. Session 监听器:

  1. HttpSessionListener:监听 HttpSession 的创建或销毁

    • HttpSession 创建时:
      void sessionCreated (HttpSessionEvent event);
    • HttpSession 销毁时:
      void sessionDestroyed (HttpSessionEvent event);
  2. HttpSessionAttributeListener:监听 HttpSession 的属性的添加、删除或者替换

    • HttpSession 属性添加时:
      void attributeAdded (HttpSessionBindingEvent event);
    • HttpSession 属性删除时:
      void attributeRemoved (HttpSessionBindingEvent event);
    • HttpSession 属性替换时:
      void attributeReplaced (HttpSessionBindingEvent event);
  3. HttpSessionActivationListener:分布式应用中,Session 可能被序列化或者被激活

    • Session 属性激活时:
      void sessionDidActivate (HttpSessionEvent event);
    • Session 属性序列化时:
      void sessionWillPassivate (HttpSessionEvent event);
  4. HttpSessionBindingListener:监听是否有 Session 进行了绑定或者取消绑定

III. ServletRequest 监听器:

  1. ServletRequestListener:监听 ServletRequest 的创建和销毁(可用来检测一个请求所花费的时间)

    • 当发起一个 HTTP 请求时:
      void requestInitialized (ServletRequestEvent event);
    • 当 ServletRequest 被销毁时:
      void requestDestroyed (ServletRequestEvent event);
  2. ServletRequestAttributeListener:监听 ServletRequest 的添加、删除或者修改

    • 当 ServletRequest 的某个属性被添加时:
      void attributeAdded (ServletRequestAttributeEvent event);
    • 当 ServletRequest 的某个属性被删除时:
      void attributeRemoved (ServletRequestAttributeEvent event);
    • 当 ServletRequest 的某个属性被替换时:
      void attributeReplaced (ServletRequestAttributeEvent event);