1.首先创建拦截器类:
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 {@Overridepublic 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;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("请求处理完成");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {log.info("请求完全结束");if (ex != null) {log.error("请求过程中发生错误:", ex);}}
}
2. 创建拦截器配置类:
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;}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(requestInterceptor).addPathPatterns("/**") // 拦截所有请求.excludePathPatterns( // 排除不需要拦截的路径"/swagger-ui/**", // swagger"/v3/api-docs/**", // swagger"/error", // 错误页面"/static/**", // 静态资源"/*.ico" // 图标文件);}
}
3.创建一个测试控制器:
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!";}
}