Skip to content

创建一个Spring Boot拦截器(Interceptor)用于打印每个HTTP请求的信息是一种有效的方法来帮助开发者监控和调试应用。以下是一个详细的步骤教程,教你如何在Spring Boot项目中实现这个功能。

步骤 1: 创建拦截器类 ​

  1. 创建拦截器: 在你的项目中,选择合适的包(如com.dhcc.common.interceptor)创建一个新的Java类,命名为RequestLoggingInterceptor。
java
package com.dhcc.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(RequestLoggingInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
log.info("Request URL: {}, Method: {}, Remote Address: {}",
request.getRequestURL(),
request.getMethod(),
request.getRemoteAddr());
return true; // 如果返回true则继续向下执行,返回false则中断执行
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理后进行调用,但在视图被渲染之前(Controller方法调用之后)
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了视图执行
}
}
### 步骤 2: 注册拦截器

2. **注册拦截器**: 在你的Spring Boot配置类中注册这个拦截器。可以选择现有的配置类或创建一个新的配置类。这里我们在`com.dhcc.common.config`包下创建一个新的配置类`WebMvcConfig`。

```java
package com.dhcc.common.config;

import com.dhcc.common.interceptor.RequestLoggingInterceptor;
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 WebMvcConfig implements WebMvcConfigurer \{

@Autowired
private RequestLoggingInterceptor requestLoggingInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) \{
// 添加拦截器到Spring MVC拦截器链
registry.addInterceptor(requestLoggingInterceptor).addPathPatterns("/**"); // 对所有请求都拦截
\}
\}
### 步骤 3: 验证拦截器

3. **启动应用**并测试拦截器是否正常工作。可以通过发送HTTP请求到你的服务端点,并检查日志输出是否包含了请求的URL、方法和来源IP。

### 总结

通过上述步骤,你已成功创建并注册了一个拦截器,它会在每个HTTP请求被处理前打印请求的详细信息,这对于调试和监控应用非常有用。确保拦截器的日志级别和输出格式符合你的开发需求。

本站总访问 — 次