springboot 整合 ServletRequestListener监听器
Listener是在servlet2.3中加入的,主要用于对Session,request,context等进行监控。使用Listener需要实现响应的接口。触发Listener事件的时候,会自动调用Listener的方法。
常用的监听接口
- HttpSessionListener:监听HttpSession的操作,监听session的创建和销毁
- ServletRequestListener:监听request的创建和销毁
- ServletContextListener:监听context的创建和销毁
现在整合的是springboot 整合ServletRequestListener
- 写个RequestListener类
package com.study.cdmy.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
/**
* 监听器
*
* @WebListener 此注解声明此类为listener,无需再进行配置,唯一注意的是,
* 使用注解的方式声明Listener时,需要在main函数类上添加@ServletComponentScan(basePackages='此处写明类地址,格式为包名+类名')
*/
@WebListener//此注解声明此类为listener,无需再进行配置,唯一注意的是,使用注解的方式声明Listener时,需要在main函数类上添加
public class RequestListener implements ServletRequestListener {
public static Integer count = 0;
@Override
public void requestDestroyed(ServletRequestEvent sre) {
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
ServletContext aa = sre.getServletContext();
System.out.println("访问次数为"+count);
count++;
}
}
- 在main方法上面添加注解
@ServletComponentScan(basePackages = “com.study.cdmy”)
package com.study.cdmy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan(basePackages = "com.study.cdmy")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("启动成功");
}
}
- 写个测试类测试
package com.study.cdmy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "test")
public class TestController {
@RequestMapping("/accessVisit")
public String AccessVisit(){
return "success";
}
}
- 访问http://127.0.0.1:8080/test/accessVisit查看控制台结果

以上就是springboot整合ServletRequestListener的过程
源码springboot整合ServletRequestListener源码分支
本文详细介绍了如何在SpringBoot项目中整合ServletRequestListener监听器,包括创建监听器类、使用@WebListener注解及在主类中添加@ServletComponentScan注解的步骤。
2794

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



