第六章 SpringBoot拦截器实战和Servlet3.0自定义Filter和Listener
06-3 Servlet3.0注解的自定义原生Listener监听器实战
监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。通俗的讲,监听器就比如你盯着一盘好吃的,有人拿你的吃的的时候,你会立马采取相应的行动。
常用的监听器:servletContextListener、httpSessionListener、servletRequestListener
1.servletRequestListener
package com.lcz.spring_demo12.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
/**
* @author : codingchao
* @date : 2021-11-23 13:37
* @Description:
**/
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("servletrequest监听器触发了");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("servletrequest监听器销毁了");
}
}
给启动类添加注解@ServletComponetScan。
package com.lcz.spring_demo12;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringDemo12Application {
public static void main(String[] args) {
SpringApplication.run(SpringDemo12Application.class, args);
}
}
以一个请求为例


请求结束,监听器也随之结束。
2.ServletContextListener
package com.lcz.spring_demo12.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* @author : codingchao
* @date : 2021-11-23 13:45
* @Description:
**/
@WebListener
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContextListener触发了");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContextListener销毁了");
}
}
启动过程中被触发。

本文详细介绍了如何在SpringBoot中使用拦截器以及Servlet3.0中的原生Listener,包括ServletRequestListener和ServletContextListener的实现和应用,以及它们在请求生命周期中的触发时机。
773

被折叠的 条评论
为什么被折叠?



