6.监听器

一、监听器概念

  1. 事件源:发生事件的对象。
  2. 监听器:是一个接口,监听事件源上要发生的动作
  3. 事件:事件对象一般是作为监听器方法的参数存在的,它封装了发生事件的对象

二、Servlet中提供的监听器(8个)

八个监听器分类:

1.监听ServletContext、HttpSession、ServletRequest对象的创建和销毁的监听器。

(1).ServletContextListener:监听ServletContext对象的创建和销毁,这个过程发生在项目启动和关闭的时候

(2).HttpSessionListener:监听HttpSession对象的创建和销毁。 创建:第一次调用request.getSession()时。 销毁:1、主动调用invalidate()方法 2、超时

(3).ServletRequestListener:监听ServletRequest对象的创建和销毁。 访问的时候创建,响应结束的时候销毁

2.监听ServletContext、HttpSession、ServletRequest对象中域变化(新来的,替换的,删除的)的监听器。 (1).ServletContextAttributeListener: (2).HttpSessionAttributeListener:使用的场景很少 (3).ServletRequestAttributeListener:使用的场景很少

3.感知型监听器:谁实现了这些接口,谁就能感知自己被怎么着了。这种监听器不需要注册。 (1).HttpSessionActivationListener:感知自己何时随着HttpSession对象钝化和活化 (2).HttpSessionBindingListener:感知自己何时被HttpSession对象绑了(绑在域中)和解绑了。

编写步骤: 1、编写一个类实现某个监听器接口 2、在web.xml中注册监听器 cn.itcast.listener.ServletContextDemoListener


文章信息

张雪随笔
master
Homepage
Issues
Download

This Software is under the terms of The Unlicense.