Listener
Listener
监听器使用的感受类似于JS中的事件,被观察的对象发生某些情况时,自动触发代码的执行
监听器监听的对象只有三大域对象,不监听web项目的其他组件
监听器的分类
web中定义八个监听器接口作为监听器的规范
Application域
- ServletContextListener:监听Application域的创建和销毁
- ServletContextAttributeListener:监听Application域中数据变化
session域
- HttpSessionListener:监听Session域的创建和销毁
- HttpSessionAttributeListener:监听Session域中数据变化
- HttpSessionBindingListener:绑定行为的监听器接口
- HttpSessionActivationListener:钝化和活化监听器接口
request域
- ServletRequestListener:监听Request域的创建和销毁
- ServletRequestAttributeListener::监听Request域中数据变化
Application域的监听器
ServletContextListener
监听ServletContext对象的创建与销毁
| 方法名 | 说明 |
|---|---|
| contextInitialized(ServletContextEvent sce) | ServletContext创建时调用 |
| contextDestroyed(ServletContextEvent sce) | ServletContext销毁时调用 |
ServletContextEvent对象代表从ServletContext对象身上捕获到的事件,通过这个事件对象我们可以获取到ServletContext对象
ServletContextAttributeListener
监听ServletContext中属性的添加、移除和修改
| 方法名 | 说明 |
|---|---|
| attributeAdded(ServletContextAttributeEvent scab) | 向ServletContext中添加属性时调用 |
| attributeRemoved(ServletContextAttributeEvent scab) | 从ServletContext中移除属性时调用 |
| attributeReplaced(ServletContextAttributeEvent scab) | 当ServletContext中的属性被修改时调用 |
注:当调用attributeReplaced方法时,使用scae对象获取的值时被修改前的值
1 | |
ServletContextAttributeEvent对象
代表属性变化事件
| 方法名 | 说明 |
|---|---|
| getName() | 获取修改或添加的属性名 |
| getValue() | 获取被修改或添加的属性值 |
| getServletContext() | 获取ServletContext对象 |
注解启动监听器
在监听器类上添加注解WebListener即可
1 | |
同一个监听器可实现多个接口,实现监听多个功能
1 | |
HttpSessionActivationListener
session对象在服务端是以对象的形式存储于内存的,session过多,服务器内存也不够
为了分摊内存压力并且为了保证session重启不丢失,我们可以设置将session进行钝化处理
钝化(序列化):内存 -> 硬盘
活化(反序列化):硬盘 ->内存
我们要监听某个session的钝化和活化,就将其属性作为参数存入session对象中
1 | |
Listener
http://blog.170827.xyz/2024/04/24/Listener/