Java Listener

Servlet的Listener监听器包括三种类型:


1、ServletContextListener    监听ServletContext对象

publicvoid contextInitialized(ServletContextEvent event);   

publicvoid contextDestoryed(ServletContextEvent event);  


2、HttpSessionListener 监听Session对象

publicvoid sessionCreated(HttpSessionEvent event);   

publicvoid sessionDestoryed(HttpSessionEvent event);  

3、HttpRequestListener 监听Request对象

publicvoid requestinitialized(ServletRequestEvent event);   

publicvoid requestDestoryed(ServletRequestEvent event);  


Web.xml文件配置

Xml代码
  1. <listener>  
  2.     <listener-class>listener.MyListener</listener-class>  
  3. </listener>  
<listener>
        <listener-class>listener.MyListener</listener-class>
</listener>


1.2    Listener按属性分类
按照监听事件类型划分分为如下类型:
1、    用于监听域对象自身的创建和销毁的事件监听器。
2、    用于监听域对象的属性的增加和删除的事件监听器。
3、    用于监听绑定到HttpSession域中的某个对象的状态的事件监听器。
1.2.1    监听对象的属性事件监听器接口

1、    attributeAdd当被监听域对象中增加属性时会调用该系列监听器

publicvoid attributeAdded(ServletContextAttributeEvent event);
publicvoid attributeAdded(HttpSessionBindingEvent event);
publicvoid attributeAdded(ServletRequestAttributeEvent event);  


2、    attributeRemoved当被监听域对象中删除属性时会调用该系列监听器

publicvoid attributeRemoved(ServletContextAttributeEvent event);   
publicvoid attributeRemoved(HttpSessionBindingEvent event);
publicvoid attributeRemoved(ServletRequestAttributeEvent event);  

3、    attributeReplaced当被监听域对象中属性变更时时会调用该系列监听器
 
publicvoid attributeReplaced(ServletContextAttributeEvent event); 
publicvoid attributeReplaced(HttpSessionBindingEvent event);
publicvoid attributeReplaced(ServletRequestAttributeEvent event);  



注:使用属性监听器需要继承如下接口,实现以上方法

ServletContextAttributeListener,  

HttpSessionAttributeListener,   

ServletRequestAttributeListener  


1.2.2    感知Session绑定的事件监听器
保存到Session域中的对象可以有多种状态:
1、    绑定到Session域中
2、    从Session域中解除绑定
3、    Session对象持久化到存储设备
4、    Session对象从一个存储设备中恢复
可以使用

Java代码
  1. HttpSessionBindingListener、HttpSessionActivationListener  

两个监听接口实现JavaBean对象的绑定,从而了解JavaBean对象在Session域的状态。

  1. HttpSessionBindingListener   
  2. publicvoid valueBound(HttpSessionBindingEvent event);   
  3. publicvoid valueUnbound(HttpSessionBindingEvent event);   
  4. HttpSessionActivationListener   
  5. publicvoid sessionWillPassivate(HttpSessionEvent event);  
    注:当Session对象持久化到文件系统时,激活上面方法。
publicvoid sessionDidActivate(HttpSessionEvent event);  


注:当Session对象从文件系统恢复时,激活上面方法。

原文地址:https://www.cnblogs.com/fangj/p/2239317.html