在Servlet技术中已经定义了一些事件,并且可以针对这些事件来编写相关的事件监听器,从而对事件做出相应处理
例如:在Web应用程序启动和关闭时执行一些任务,监控Session的创建和销毁,都可以通过监听器来实现
Servlet 监听器简介
利用Listener接口监听在容器中的某个执行程序,并且根据其应用程序的需求做出适当的响应,Servlet和JS中的8个Listener接口和6个Event类
Servlet 上下文监听
Servlet上下文监听可以监听ServletContext对象的创建,删除以及属性添加,删除和修改操作,该监听器需要用到以下两个接口:
-
ServletContextListener接口
该接口存放在javax.servlet包中,主要实现监听ServletContext的创建和删除,这个接口提供了两个方法: -
contextInitialized(ServletContextEvent event)方法:通知正在监听的对象,应用程序已经被加载及初始化
-
contextDestroy(ServletContextEvent event)方法:通知正在收听的对象,应用程序已经被关闭
-
ServletAttributeListener接口
该接口存放在javax.servlet包中,主要监听ServletContext属性的增加,删除和修改,该接口有以下3个方法: -
attributeAdded(ServletContextAttributeEvent event):当有对象加入Application的范围时,通知正在监听的对象
-
attributeReplaced(ServletContextAttributeEvent event):当在Application的范围有对象取代另一个对象时,通知正在收听的对象
-
attributeRemoved(ServletContextAttributeEvent event):当有对象从Application的范围移除时,通知正在监听的对象
代码示例:
- 创建监听器
public class MyContextListener implements ServletContextListener{
// 代码...
}
- 为使Web容器在Web应用程序启动时通知MyContextListener,需要在web.xml文件中使用<listener>元素来配置监听器类
<listener>
<listener-class>com.listener.MyContextListener</listener-class>
</listener>
HTTP会话监听
http会话监听有4个接口可以进行监听:
-
HttpSessionListener接口
该接口实现监听HTTP会话创建,销毁,有以下两个方法: -
sessionCreated(HttpSessionEvent event)方法:通知正在监听的对象,session已经被加载及初始化
-
sessionDestroyed(HttpSessionEvent event)方法
(HttpSessionEvent类的主要方法时getSession(),可以使用该方法回传一个session对象) -
HttpSessionAttributeListener接口
该接口实现监听HTTP会话中属性的设置请求,有以下3个方法: -
attributeAdded(HttpSessionBindingEvent event)方法:当有对象加入session范围时,通知正在收听的对象
-
attributeReplaced(HttpSessionBindingEvent event)方法:当在session的范围内有对象取代另一位对象时,通知监听对象
-
attributeRemoved(HttpSessionBindingEvent event)方法:当有对象从session范围内移除时,通知正在收听的对象
(HttpSessionBindingEvent类主要有3个方法:getName(),getSession(),getValues()) -
HttpBindingListener接口
HttpBindingListener接口实现监听HTTP会话中对象的绑定信息,它是唯一一个不需要在web.xml文件中设定Listener的,有以下两个方法: -
valueBound(HttpSessionBingdingEvent event)方法:当有对象加入session的范围时会被自动调用
-
valueUnBound(HttpSessionBindingEvent event)方法:当有对象从Session的范围内移除时会被自动调用
-
HttpSessionActivationListener接口
该接口实现监听HTTP会话active和passivate,有以下2个方法 -
sessionDidActivate(HttpSessionEvent event)方法:通知正在监听的对象,它的session已经变为有效状态
-
sessionWillPassivate(HttpSessionEvent event)方法:通知正在监听的对象,它的session已经变为无效状态
Servlet请求监听
在Servlet2.4规范中新增加了一个技术,就是可以监听客户端的请求,一旦能够在监听程序中获取客户端的请求,就可以对请求进行统一处理。实现客户端的请求和请求参数设置的监听器需要实现以下两个接口:
-
ServletRequestListener接口
-
requestInitialized(ServletRequestEvent event)方法:通知正在监听的对象,ServletRequest已经被加载和初始化
-
requestDestroyed(ServletRequestEvent event)方法:ServletRequest已经被关闭
-
ServletRequestAttributeListener接口:
-
attributeAdded(ServletRequestAttributeEvent event)方法:当有对象加入request的范围时,通知正在监听的对象
-
attributeReplaced(ServletRequestAttributeEvent event)方法:当在request的范围内有对象取代另一个对象时,通知正在收听的对象
-
attributeRemoved(ServletRequestAttributeEvent event)方法:当有对象从request的范围移除时,通知正在收听的对象