为了在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);