Spring Boot实战:拦截器和监听器的应用指南

当使用Spring Boot时,我们可以通过拦截器(Interceptor)和监听器(Listener)来实现对请求和响应的处理。拦截器和监听器提供了一种可插拔的机制,用于在请求处理过程中进行自定义操作,例如记录日志、身份验证、权限检查等。下面通过提供一个示例,展示如何使用拦截器和监听器来记录请求日志。

首先,我们创建一个简单的Spring Boot项目,并添加所需的依赖。在这个示例中,我们将使用Spring Boot Starter Web。

  1. 创建一个Spring Boot项目并添加依赖

创建一个新的Spring Boot项目,可以使用Spring Initializr(https://start.spring.io/)进行初始化。在"Dependencies"中添加"Spring Web"依赖,并生成项目。

  1. 创建拦截器

在项目中创建一个名为 RequestLoggingInterceptor 的类,实现 HandlerInterceptor 接口。这个拦截器将记录请求的URL、HTTP方法和时间戳。

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestLoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求的URL、HTTP方法和时间戳
        System.out.println("RequestLoggingInterceptor"+"启动了");
        System.out.println("Request URL: " + request.getRequestURL());
        System.out.println("HTTP Method: " + request.getMethod());
        System.out.println("Timestamp: " + System.currentTimeMillis());
        return true;
    }
}
  1. 注册拦截器

在Spring Boot应用程序的配置类中,注册拦截器,使其生效。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final RequestLoggingInterceptor requestLoggingInterceptor;

    @Autowired
    public WebConfig(RequestLoggingInterceptor requestLoggingInterceptor) {
        this.requestLoggingInterceptor = requestLoggingInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器
        registry.addInterceptor(requestLoggingInterceptor);
    }
}
  1. 创建监听器

在项目中创建一个名为 RequestListener 的类,实现 ServletRequestListener 接口。这个监听器将在请求的开始和结束时记录日志。

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        System.out.println("RequestListener"+"启动了");
        // 记录请求的URL、HTTP方法和时间戳
        System.out.println("Request URL: " + request.getRequestURL());
        System.out.println("HTTP Method: " + request.getMethod());
        System.out.println("Timestamp: " + System.currentTimeMillis());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // 请求处理完成后的操作
        System.out.println("Request processing completed.");
    }
}
  1. 编写控制器

创建一个简单的控制器来模拟请求处理

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user")
    public String getUser() {
        return "Get User";
    }

    @PostMapping("/user")
    public String saveUser(@RequestBody String user) {
        return "Save User: " + user;
    }
}

  1. 在启动类或配置类上添加 @ServletComponentScan 注解

启用对监听器的支持

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class HelloWorldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApplication.classargs);
    }
}

  1. 运行应用程序

现在,你可以运行Spring Boot应用程序并访问一些URL,观察控制台输出的日志信息。每次发起请求时,拦截器和监听器都会捕获请求并输出相关的日志。示例效果如下:

alt

本文由 mdnice 多平台发布

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值