JavaWeb——Listener监听器

来源:互联网 发布:淘宝如何转接人工客服 编辑:程序博客网 时间:2024/05/16 17:38

1、Listener监听器的概念

监听器是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用/属性改变,当被监听对象发生上述事件时,监听器某个方法被执行。

这里写图片描述

2、JavaWeb中的监听器

2.1 监听器分类

javaweb中的监听器用来监听web应用程序中的ServletContext,HttpSession和ServletRequest等域对象的创建、销毁及域对象中属性发生修改的事件。

针对三个对象的操作,分为三种类型:

  • 监听域对象自身的创建和销毁。
  • 监听域对象中属性的增加和删除。
  • 监听域对象中某个属性的改变。

2.2 监听器接口

2.2.1 监听ServletContext

ServletContextListener接口—(监听)—>ServletContextEvent事件

  • void contextInitialized(ServletContextEvent event) 应用加载到容器时被调用
  • void contextDestroyed(ServletContextEvent event) 应用关闭时被调用

ServletContextAttributeListener接口—(监听)—>ServletContextAttributeEvent事件

  • void attributeAdded(ServletContextAttributeEvent event) 新增属性时被调用
  • void attributeReplaced(ServletContextAttributeEvent event) 更新属性时被调用
  • void attributeRemoved(ServletContextAttributeEvent event) 删除属性时被调用

2.2.2 监听HttpSession

HttpSessionListener接口—(监听)—>HttpSessionEvent事件

  • void sessionCreated(HttpSessionEvent event) 新建HttpSession时被调用
  • void sessionDestroyed(HttpSessionEvent event) 销毁HttpSession时被调用

HttpSessionAttributeListener接口—(监听)—>HttpSessionBindingEvent事件

  • void attributeAdded(HttpSessionBindingEvent event) 新增属性时被调用
  • void attributeReplaced(HttpSessionBindingEvent event) 更新属性时被调用
  • void attributeRemoved(HttpSessionBindingEvent event) 删除属性时被调用

2.2.3 监听ServletRequest

ServletRequestListener接口—(监听)—>ServletRequestEvent事件

  • void requestInitialized(ServletRequestEvent event) 创建request对象时被调用
  • void requestDestroyed(ServletRequestEvent event) 销毁request对象时被调用

2.3 Listener的一般使用步骤

  1. 编写一个实现某个Listener接口的监听器类。
  2. 实现监听器类中相应的方法,针对监听到的事件作出反应。
  3. 将监听器类配置到web.xml文件中。
0 0