Servlet规范定义了监听ServletContext,HttpSession,HttpServletRequest这三个对象中属性变动信息事件监听器。web
这三个监听器接口分别:apache
public interface HttpSessionAttributeListener extends EventListener public interface ServletContextAttributeListener extends EventListener public interface ServletRequestAttributeListener extends EventListener
三个接口中都定义了三个方法来处理被监听对象中属性的增长,删除和替换的事件,同一个事件在这三个接口中对应的方法名称彻底相同,只是接受的参数类型不一样。服务器
当向监听器对象中增长一个属性时,web容器就调用事件监听器的attributeAdded方法进行响应,这个方法接受一个事件类型的参数,监听器能够经过这个参数来获取正在增长属性的域对象和被保存到域对象中的属性对象。session
当删除被监听对象中的一个属性时,web容器调用事件监听器的attributeRemoved方法。spa
当监听器的域对象中的某个属性被替换时,web容器调用事件监听器的attributeReplaced方法。code
各个域属性监听器中的完整语法定义:xml
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域中的对象能够有多种状态:blog
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>