Listener监听器

在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为 ServletContext, HttpSession 和 ServletRequest 这三个域对象

一、注册 Servlet 监听器有 2 种方式:

1、在 web.xml 中注册监听器(MySessionListener需要实现监听类)

<listener>
<listener-class>ll.listener.MySessionListener</listener-class>
</listener>

2、使用 @WebListener 注解注册监听器(MySessionListener需要实现监听类)

springboot的Application启动类:需要注解@ServletComponentScan

 

二、监听器的分类

1、监听对象创建和销毁的监听器

ServletContextListener

HttpSessionListener

ServletRequestListener

2、监听属性变更的监听器

ServletContextAttributeListener

HttpSessionAttributeListener

ServletRequestAttributeListener

3、监听 Session 中对象状态改变的监听器

HttpSessionBindingListener

HttpSessionActivationListener

使用 HttpSessionBindingListener 和 HttpSessionActivationListener 时,不必进行注册,直接创建 Java 类实现这两个接口即可

 

三、自定义事件监听

1、定义自己的事件:MyApplicationEvent,继承ApplicationEvent

public class MyApplicationEvent extends ApplicationEvent{

        public MyApplicationEvent(Object source) {

            super(source);
        }
}

2、事件监听:实现ApplicationListener类,重写onApplicationEvent方法

①方法内判断事件类型

@Component
public class MyApplicationListener implements ApplicationListener{

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof MyApplicationEvent) {
            System.out.println("MyApplicationListener...............");
        }
    }
}

②或者指定事件类型

@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>{

    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        System.out.println("MyApplicationListener...............");
    }

}

 3、事件调用

@RestController
public class ApplicationEventController {

    @Autowired
    ApplicationContext context;

    @RequestMapping("/appEvent")
        public void appEvent() {
         context.publishEvent(new MyApplicationEvent("object"));

    }
}

 

四、说明

ApplicationListener是基于spring框架实现,ServletContextListener、HttpSessionListener、ServletRequestListener等都是基于Servlet实现,以上这些类的共同点是都继承了EventListener接口类。

 

posted @ 2022-04-06 10:01  #庄生晓梦  阅读(59)  评论(0编辑  收藏  举报