springboot整合拦截器

1.首先创建拦截器类:

java 复制代码
package com.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("请求开始,URI: {}, Method: {}", requestURI, method);
        
        // 获取请求头中的token(如果有)
        String token = request.getHeader("Authorization");
        if (token != null) {
            log.info("Token: {}", token);
        }
        
        // 返回true表示继续执行,返回false表示中断请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("请求处理完成");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("请求完全结束");
        if (ex != null) {
            log.error("请求过程中发生错误:", ex);
        }
    }
}
  1. 创建拦截器配置类:
java 复制代码
package com.example.config;

import com.example.interceptor.RequestInterceptor;
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 WebMvcConfig implements WebMvcConfigurer {

    private final RequestInterceptor requestInterceptor;

    public WebMvcConfig(RequestInterceptor requestInterceptor) {
        this.requestInterceptor = requestInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestInterceptor)
                .addPathPatterns("/**")         // 拦截所有请求
                .excludePathPatterns(           // 排除不需要拦截的路径
                    "/swagger-ui/**",           // swagger
                    "/v3/api-docs/**",          // swagger
                    "/error",                   // 错误页面
                    "/static/**",               // 静态资源
                    "/*.ico"                    // 图标文件
                );
    }
}

3.创建一个测试控制器:

java 复制代码
package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api")
public class TestController {

    @GetMapping("/test")
    public String test() {
        log.info("测试接口被调用");
        return "Hello from test endpoint!";
    }
}
相关推荐
SoniaChen333 分钟前
Rust基础-part3-函数
开发语言·后端·rust
一个天蝎座 白勺 程序猿5 分钟前
飞算JavaAI进阶:重塑Java开发范式的AI革命
java·开发语言·人工智能
代码的余温8 分钟前
Spring Boot集成Logback日志全攻略
xml·spring boot·logback
全干engineer8 分钟前
Flask 入门教程:用 Python 快速搭建你的第一个 Web 应用
后端·python·flask·web
前端 贾公子9 分钟前
tailwindCSS === 使用插件自动类名排序
java·开发语言
没有bug.的程序员14 分钟前
JAVA面试宝典 -《Spring Boot 自动配置魔法解密》
java·spring boot·面试
William一直在路上28 分钟前
SpringBoot 拦截器和过滤器的区别
hive·spring boot·后端
hnlucky1 小时前
《Nginx + 双Tomcat实战:域名解析、静态服务与反向代理、负载均衡全指南》
java·linux·服务器·前端·nginx·tomcat·web
hnlucky1 小时前
同时部署两个不同版本的tomcat要如何配置环境变量
java·服务器·http·tomcat·web
小马爱打代码1 小时前
Spring Boot 3.4 :@Fallback 注解 - 让微服务容错更简单
spring boot·后端·微服务