一、监听器概述
(1)servlet 事件监听器支持在servletContext、httpSession和servletRequest对象的状态改变时的事件通知。
(2)对于同一事件类型,可以有多个监听器类监听,开发者可以为每个事件类型指定容器触发这些监听器的次序。
(3)servlet监听器的主要目的是给web应用增加事件处理机制,以便更好的监视和控制web应用的变化。
二、监听web应用程序范围内的事件
(1)servletContextListener
用于监听web应用程序启动和销毁的事件,监听器需要实现java.servlet.ServletContextListener接口。
void contextInitialized(servletContextEvent sce)通知正在接受的对象,应用程序已经被加载。
void contextDestroyed(servletContextEvent sec)通知正在接受的对象,应用程序已经被销毁。
(2)servletContextAttributeListener
用于监听web应用属性改变事件,包括:增加属性,删除属性,修改属性,监听器需要实现java.servlet.servletContextAttributeListener接口。
void attributeadded(servletContextAttributeListenerEvent scab)若有属性加入,通知正在监听的对象。
void attributeRemoved(servletContextAttributeListenerEvent scab)若有属性删除,通知正在监听的对象。
void attributeRepalaced(servletContextAttributeListenerEvent scab)若有属性修改,通知正在监听的对象。
三、监听会话范围内事件
(1)HttpSessionBindingListener接口
void valueBound()当对象绑定到session中,servlet容器调用该方法来通知该对象。
void valueUnbound()当对象从session中删除时,servlet容器调用该方法来通知该对象。
(2)HttpSessionAttributeListener接口
主要监听Httpsession中的属性操作。
当在session中增加一个属性时,激发attributeadded()方法。
当在session中删除一个属性时,激发attributeremoved()方法。
当在session属性被重新设置时,激发attributereplaced()方法。
(3)HttpsessionListener接口
当创建一个session时,激发sessionCreated()方法,当销毁一个session时,激发sessionDestroyed()方法。
(4)HttpSessionActivationListener接口
public void sessionDidActivate()会话被激活。
public void sessionWillPassivate()会话被迁移。