监听器主要用来监听对象的创建,属性的变化,是一个实现特定接口的普通Java类
与ServletContext相关监听器
单个Web站点的资源都共享一个ServletContext,通过该对象可以存取应用程序的全局对象以及初始化阶段的变量
- ServletContextListener接口(生命周期)
• 实现了该接口的程序,当应用程序启动时,会自动开始监听工作
• 首先调用contextInitialized()方法接收对应的ServletContextEvent事件
• 当应用从容器中移除时,会自动调用contextDestroyed()方法
• 以上两个方法都会接收到ServletContextEvent事件对象,该对象可以调用getServletContext()方法取得ServletContext对象(全局对象)
- ServletContextAttributeListener接口(属性变化)
实现该接口的程序,能够监听ServletContext属性的变化
ServletContextAttributeEvent的主要方法
– getName()
– getValue()
• attributeReplaced()方法中,getName()与getValue()是取之前的值
与HttpSession相关监听器
- HttpSessionListener
监听Session对象的创建与销毁,当有Session对象产生或销毁时,会自动调用sessionCreated()或sessionDestroyed()两个方法
• HttpSessionListener接口与HttpSessionActivationListener接口都使用HttpSessionEvent事件对象
• HttpSessionEvent类主要的方法:
– getSession() - HttpSessionActivationListener
当Session被储存起来,并且等待转移至另一个JVM,这段时间称为失效状态。若Session中的属性对象实现HttpSessionActivationListener接口时,Container会自动调用sessionWillPassivate()方法通知该对象的Session已变成失效状态,当Session被转移至其他JVM之后,它又成为有效状态。此时Container会自动调用sessionDidActivate()方法通知该对象的Session已变成有效状态 - HttpSessionAttributeListener
– HttpSessionAttributeListener会监听Session属性的变化,功能与ServletContextAttributeListener接口类似,包含三个方法
– attributeAdded()
– attributeReplaced()
– attributeRemove()
HttpSessionBindingEvent事件
HttpSessionBindingEvent事件主要有三个方法:
getName() ;getSession();getValue(); - HttpSessionBindingListener(添加特定对象时才监听)
–valueBound(HttpSessionBindingEvent e) 属性绑定
–valueUnbound(HttpSessionBindingEvent e) 解除绑定
HttpSessionBindingListener接口是唯一不需要在web.xml中设定的Listener
- HttpSessionAttributeListener与HttpSessionBindingListener的不同在于:
– 前者监听Web站点所有Session范围的变化
– 后者只监听Session范围内实现了HttpSessionBindingListener接口的对象移入移出
与ServletRequest相关监听器
- ServletRequestListener接口
当有请求产生或销毁,会自动调用该接口实现的requestInitialized()或requestDestroyed()方法 - ServletRequestEvent的主要方法:
getServletContext()
getServletRequest() - ServletRequestAttributeListener
该接口监听Request范围的变化,有三个主要方法: attributeAdded();attributeReplaced();attributeRemoved()
• ServletRequestAttributeEvent主要方法:getName();getValue()
监听器的应用
• ServletContext范围的监听器可以进行一些初始化的动作,如:当Web应用启动的时候进行全局配置
• Session范围的监听器对一个会话过程(与客户端关联)中所产生的事件进行响应,可以对客户端信息的变化进行跟踪
• Request范围的监听器可以监听用户的每次请求