springboot 整合 ServletRequestListener监听器

本文详细介绍了如何在SpringBoot项目中整合ServletRequestListener监听器,包括创建监听器类、使用@WebListener注解及在主类中添加@ServletComponentScan注解的步骤。

springboot 整合 ServletRequestListener监听器

Listener是在servlet2.3中加入的,主要用于对Session,request,context等进行监控。使用Listener需要实现响应的接口。触发Listener事件的时候,会自动调用Listener的方法。

常用的监听接口

  • HttpSessionListener:监听HttpSession的操作,监听session的创建和销毁
  • ServletRequestListener:监听request的创建和销毁
  • ServletContextListener:监听context的创建和销毁
    现在整合的是springboot 整合ServletRequestListener
  1. 写个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++;
	}

}

  1. 在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("启动成功");
    }

}

  1. 写个测试类测试
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";
	}
}

  1. 访问http://127.0.0.1:8080/test/accessVisit查看控制台结果
    在这里插入图片描述
    以上就是springboot整合ServletRequestListener的过程
    源码springboot整合ServletRequestListener源码分支
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值