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
2
3
4
public void attributeReplaced(ServletContextAttributeEvent scae) {
ServletContext application = scae.getServletContext();
System.out.println(scae.getName() + scae.getValue() + "的值被修改为" + application.getAttribute(scae.getName()));
}

ServletContextAttributeEvent对象

代表属性变化事件

方法名 说明
getName() 获取修改或添加的属性名
getValue() 获取被修改或添加的属性值
getServletContext() 获取ServletContext对象

注解启动监听器

在监听器类上添加注解WebListener即可

1
2
3
4
5
6
7
8
9
@WebListener
public class MyApplicationListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized");
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed");
}
}

同一个监听器可实现多个接口,实现监听多个功能

1
2
3
@WebListener
public class MyApplicationListener implements ServletContextListener, ServletContextAttributeListener {
}

HttpSessionActivationListener

session对象在服务端是以对象的形式存储于内存的,session过多,服务器内存也不够

为了分摊内存压力并且为了保证session重启不丢失,我们可以设置将session进行钝化处理

钝化(序列化):内存 -> 硬盘

活化(反序列化):硬盘 ->内存

我们要监听某个session的钝化和活化,就将其属性作为参数存入session对象中

1
session.setAttribute("activationListener",new ActivationListener()); //添加钝化活化监听器


Listener
http://blog.170827.xyz/2024/04/24/Listener/
作者
XIAOBAI
发布于
2024年4月24日
许可协议