简介 JavaWeb 中的监听器
为了在 Servlet/JSP 应用程序中使用事件驱动编程(Event-Driven Programming),Servlet/JSP 提供了一套监听器的接口和类。
简单的说,监听器就是能够在某种操作发生时,检测到这种操作的发生,并且执行一定动作的操作。
Servlet/JSP 应用提供以下两种方式来创建一个监听器:
使用
WebListener注解 (简单易用,直接实现对应的 Listener 接口即可):@WebListener public class _ListenerClass_ implements _ListenerInterface_ { }在配置文件中配置
listener元素:<lisenter> <listener-class>_fully-qualified listener class_</listener-class> </lisenter>
常见的监听器以及他们所监听的事件:
I. Servlet Context 监听器:
ServletContextListener:监听 ServletContext 初始化或者销毁操作
- ServletContext 初始化时:
void contextInitialized (ServletContextEvent event); - ServletContext 销毁时:
void contextDestroyed (ServletContextEvent event);
- ServletContext 初始化时:
ServletContextAttributeListener:监听 ServletContext 的属性的添加、删除或者替换
- ServletContext 属性添加时:
void attributeAdded (ServletContextAttributeEvent event); - ServletContext 属性删除时:
void attributeRemoved (ServletContextAttributeEvent event); - ServletContext 属性替换时:
void attributeReplaced (ServletContextAttributeEvent event);
- ServletContext 属性添加时:
II. Session 监听器:
HttpSessionListener:监听 HttpSession 的创建或销毁
- HttpSession 创建时:
void sessionCreated (HttpSessionEvent event); - HttpSession 销毁时:
void sessionDestroyed (HttpSessionEvent event);
- HttpSession 创建时:
HttpSessionAttributeListener:监听 HttpSession 的属性的添加、删除或者替换
- HttpSession 属性添加时:
void attributeAdded (HttpSessionBindingEvent event); - HttpSession 属性删除时:
void attributeRemoved (HttpSessionBindingEvent event); - HttpSession 属性替换时:
void attributeReplaced (HttpSessionBindingEvent event);
- HttpSession 属性添加时:
HttpSessionActivationListener:分布式应用中,Session 可能被序列化或者被激活
- Session 属性激活时:
void sessionDidActivate (HttpSessionEvent event); - Session 属性序列化时:
void sessionWillPassivate (HttpSessionEvent event);
- Session 属性激活时:
HttpSessionBindingListener:监听是否有 Session 进行了绑定或者取消绑定
III. ServletRequest 监听器:
ServletRequestListener:监听 ServletRequest 的创建和销毁(可用来检测一个请求所花费的时间)
- 当发起一个 HTTP 请求时:
void requestInitialized (ServletRequestEvent event); - 当 ServletRequest 被销毁时:
void requestDestroyed (ServletRequestEvent event);
- 当发起一个 HTTP 请求时:
ServletRequestAttributeListener:监听 ServletRequest 的添加、删除或者修改
- 当 ServletRequest 的某个属性被添加时:
void attributeAdded (ServletRequestAttributeEvent event); - 当 ServletRequest 的某个属性被删除时:
void attributeRemoved (ServletRequestAttributeEvent event); - 当 ServletRequest 的某个属性被替换时:
void attributeReplaced (ServletRequestAttributeEvent event);
- 当 ServletRequest 的某个属性被添加时:
本文链接: https://www.nosuchfield.com/2015/12/01/introduction-to-JavaWeb-in-the-listener/
版权声明: 本博客所有文章均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!