一、什么是监听器
监听器用于监听web应用中的某些对象,信息的创建、销毁、增加、删除等动作的发生,然后做出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。
常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。
二、 监听ServletContext的变化
a.监听生命周期
ServletContextListener接口 内部方法: 初始化:contextInitialized 销毁:contextDestroyed
b.监听属性内容变化
ServletContextAttributeListener接口 内部的方法: attributeAdded:监听属性的添加 attributeRemoved:监听属性的移除 attributeReplaced:监听属性的修改
三、 监听HttpSession变化
a.监听生命周期
HttpSessionListener 内部方法: sessionCreated:监听Session对象的创建 sessionDestroyed:监听Session对象的销毁
b.监听属性内容变化
HttpSessionAttributeListener 监听HttpSession的内容的变化 内部的方法: attributeAdded:监听属性的添加 attributeRemoved:监听属性的移除 attributeReplaced:监听属性的修改
c.监听服务器的Session的钝化和活化
HttpSessionActivationListener 监听服务器的钝化和活化 内部方法: sessionWillPassivate:监听Session内部存储对象的钝化-存储 sessionDidActivate:监听Session内部存储对象的活化---读取 对应类需要实现序列化接口Serializable
d.监听对象的添加和移除
HttpSessionBindingListener 监听对象的添加和移除 内部方法: valueBound:监听对象的绑定 valueUnbound:监听对象的解除绑定
四、监听ServletRequest的变化
a.监听生命周期
ServletRequestListener 监听request对象的初始化和销毁 内部方法: 1、requestInitialized:监听request对象的初始化 2、requestDestroyed:监听request对象的销毁
b.监听属性内容变化
ServletRequestAttributeListener 监听属性内容变化 内部方法: attributeAdded:监听属性的添加 attributeRemoved:监听属性的移除 attributeReplaced:监听属性的修改
五、 监听器的2种配置
1、在web.xml中进行配置
<listener> <!--直接写出自定义的监听器的类名即可--> <listener-class>com.web.listener.RequestLeftListener</listener-class> </listener>
2注解式配置
Servlet3.0之后新增的,使用注解@WebListener进行监听器的注册