三个域对象的属性监听器

Servlet规范定义了监听ServletContext,HttpSession,HttpServletRequest这三个对象中属性变更信息事件监听器。

这三个监听器接口分别:

public interface HttpSessionAttributeListener extends EventListener
public interface ServletContextAttributeListener extends EventListener
public interface ServletRequestAttributeListener extends EventListener

三个接口中都定义了三个方法来处理被监听对象中属性的增加,删除和替换的事件,同一个事件在这三个接口中对应的方法名称完全相同,只是接受的参数类型不同。

当向监听器对象中增加一个属性时,web容器就调用事件监听器的attributeAdded方法进行响应,这个方法接受一个事件类型的参数,监听器可以通过这个参数来获取正在增加属性的域对象和被保存到域对象中的属性对象。

当删除被监听对象中的一个属性时,web容器调用事件监听器的attributeRemoved方法。

当监听器的域对象中的某个属性被替换时,web容器调用事件监听器的attributeReplaced方法。

各个域属性监听器中的完整语法定义:

public void attributeAdded(ServletRequestAttributeEvent srae);
public void attributeRemoved(ServletRequestAttributeEvent srae);
public void attributeReplaced(ServletRequestAttributeEvent srae);
public void attributeAdded(ServletContextAttributeEvent event);
public void attributeRemoved(ServletContextAttributeEvent event);
public void attributeReplaced(ServletContextAttributeEvent event) ;
public void attributeAdded(HttpSessionBindingEvent event);
public void attributeRemoved(HttpSessionBindingEvent event);
public void attributeReplaced(HttpSessionBindingEvent event);

感知Session绑定的事件监听器

保存在Session域中的对象可以有多种状态:

  • 绑定到Session中
  • 从Session中解除绑定
  • 随Session对象持久化到存储设备中
  • 随Session对象从一个存储设备中恢复

Servlet规范中定义了两个特殊的监听器接口来帮助JavaBean对象了解自已在Session域中的这些状态:

public interface HttpSessionActivationListener extends EventListener
public interface HttpSessionBindingListener extends EventListener

实现这两个接口的类不需要web.xml文件中进行注册,既是监听器又是事件源,实现的伪代码可能如下:

class Session{
    void setAttribute(String key, Object value){
        if(value instanceof HttpSessionBindingListener){
             HttpSessionBindingListener listener = (HttpSessionBindingListener)value;
             value.valueBound();
        }
        set(key, value);
    }
}

实现了HttpSessionBindingListener接口的JavaBean对象可以感知自己被绑定到Session中和从Session中删除的事件

当对象被绑定到HttpSession对象中时,web服务器调用该对象如下方法

 void valueBound(HttpSessionBindingEvent event) 

当对象从HttpSession对象中解除绑定时,web服务器调用该对象如下方法

 void valueUnbound(HttpSessionBindingEvent event) 

实现了HttpSessionActivationListener接口的JavaBean对象可以感知自己被活化和钝化的事件。

当绑定到HttpSession对象中的对象将要随HttpSession对象被钝化之前,web服务器调用如下方法 sessionWillPassivate(HttpSessionEvent se) 

当绑定到HttpSession对象中的对象将要随HttpSession对象被活化之后,web服务器调用如下方法 sessionDidActivate(HttpSessionEvent se) 

配置Session一分钟没人用到硬盘里去(META-INF下新建context.xml):

<context>
    <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
        <Store className="org.apache.catalina.session.FileStore" directory="./session"/>
    </Manager>
</context>

 

posted @ 2018-12-14 16:20  aikf  阅读(543)  评论(0编辑  收藏  举报