当前位置: 首页 > news >正文

Spring MVC HandlerInterceptor 拦截请求及响应体

Spring MVC HandlerInterceptor 拦截请求及响应体

使用Spring MVC HandlerInterceptor拦截请求和响应体的实现方案。
通过自定义LoggingInterceptorpreHandlepostHandleafterCompletion方法中记录请求信息,并利用RequestBodyCachingFilter缓存请求体以便多次读取。

具体步骤:

  1. 使用InterceptorRequest对象存储请求信息;
  2. 通过Filter实现请求体缓存;
  3. 使用RequestWrapper处理一次性读取的InputStream问题。

该方案适用于需要记录完整请求/响应信息的应用场景。

  • 前期想法
@Slf4j
public class LoggingInterceptor implements HandlerInterceptor {// create a InterceptorRequest object to store request info@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// save request header, request body into InterceptorRequest// set InterceptorRequest into request attribute, eg "InterceptorRequest"log.info("preHandle");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// get InterceptorRequest from request attribute "InterceptorRequest"// update response body, response code into InterceptorRequest// save into persistence systemif (null == ex) {log.info("afterCompletion");} else {            log.error("afterCompletion -ex - {}", ex.getMessage());}}
}
  • 将请求结果一次性塞入持久层
@Slf4j
public class LoggingInterceptor implements HandlerInterceptor {// create a InterceptorRequest object to store request info// ...// update code as below@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// get InterceptorRequest from request attribute "InterceptorRequest"// update response body, response code into InterceptorRequest// save into persistence system}
}
  • 使用 Filter 拦截获取Request Body,获取请求体
@Slf4j
public class HttpRequestContext {public static String getRequestBody(ServletRequest request) {StringBuilder builder = new StringBuilder();try (InputStream inputStream = request.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {String line;while ((null != (line = reader.readLine()))) {builder.append(line);}} catch (IOException e) {log.warn("Error reading request body", e);throw new RuntimeException(e);}return builder.toString();}
}
/*** It is a filter class used to cache request bodies, commonly employed in web applications,* especially when handling POST or PUT requests. Since the input stream (InputStream) of an **HTTP request*** can only be read once, it is necessary to cache the request body in scenarios where the content* of the request body needs to be accessed multiple times (such as logging, verification, filtering, etc.).*/
@Slf4j
public class RequestBodyCachingFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {String requestId = request.getAttribute("requestId")if (null == requestId) {requestId  = UUID.randomUUID().toString().replaceAll("-", "");}MDC.put("requestId", requestId);ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);try {// Wrap the request to cache the request bodyServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);chain.doFilter(requestWrapper, responseWrapper);} finally {responseWrapper.copyBodyToResponse();MDC.remove("requestId");}}@Getterstatic class RequestWrapper extends ContentCachingRequestWrapper {private final String requestBody;public RequestWrapper(HttpServletRequest request) {super(request);requestBody = HttpRequestContext.getRequestBody(request);}@Overridepublic ServletInputStream getInputStream() throws IOException {// Return a ServletInputStream that reads from the cached request bodyfinal ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody.getBytes());return new ServletInputStream() {@Overridepublic int read() throws IOException {return byteArrayInputStream.read();}@Overridepublic boolean isFinished() {return false;}@Overridepublic boolean isReady() {return false;}@Overridepublic void setReadListener(ReadListener listener) {}};}}
}

需要将自定义的Filter注册到FilterRegistrationBean

    @Beanpublic FilterRegistrationBean<RequestBodyCachingFilter> requestBodyCachingFilter() {FilterRegistrationBean<RequestBodyCachingFilter> registration = new FilterRegistrationBean<>();registration.setFilter(new RequestBodyCachingFilter());registration.addUrlPatterns("/*");registration.setOrder(1);return registration;}
  • 统一接口封装响应实体
@Getter
@Setter
public class ApiObj<T> {private  String code;private  String message;private  T data;public ApiObj(String code, String message, T data) {this.code = code;this.data = data;this.message = message;}public static <T> ApiObj<T> success(T data) {return new ApiObj<>("200", "success", data);}public static <T> ApiObj<T> failure(String code, String message) {return new ApiObj<>(code, message, null);}
}

封装异常返回。这样返回结果可以与对外接口提供的数据一致。
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class GlobalException {static final ObjectMapper objectMapper = new ObjectMapper();@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<ApiObj<String>> handleValidationExceptions(MethodArgumentNotValidException ex) throws JsonProcessingException {log.error("handleValidationExceptions - {}", ex.getMessage());Map<String, String> errors = new HashMap<>();ex.getBindingResult().getAllErrors().forEach((error) -> {String fieldName = ((FieldError) error).getField();String errorMessage = error.getDefaultMessage();errors.put(fieldName, errorMessage);});String message = objectMapper.writeValueAsString(errors);return new ResponseEntity<>(ApiObj.failure(String.valueOf(HttpStatus.BAD_REQUEST.value()), message), HttpStatus.BAD_REQUEST);}@ExceptionHandler(value = Exception.class)public ResponseEntity<ApiObj<String>> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {log.error("defaultErrorHandler - {}", e.getMessage());Map<String, String> map = Map.of("k1", "k2");String message = objectMapper.writeValueAsString(map);return new ResponseEntity<>(ApiObj.failure(String.valueOf(HttpStatus.BAD_REQUEST.value()), message), HttpStatus.BAD_REQUEST);}@ExceptionHandler(value = IOException.class)public ResponseEntity<ApiObj<String>> defaultIOException(HttpServletRequest req, IOException e) throws Exception {log.error("defaultIOException - {}", e.getMessage());Map<String, String> map = Map.of("k3", "k4");String message = objectMapper.writeValueAsString(map);return new ResponseEntity<>(ApiObj.failure(String.valueOf(HttpStatus.BAD_REQUEST.value()), message), HttpStatus.BAD_REQUEST);}
}

= 完整更新 LoggingInterceptor

@Slf4j
public class LoggingInterceptor implements HandlerInterceptor {final static String INTERNAL_REQUEST_BODY = "INTERNAL_REQUEST_BODY";@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// save request header, request body into InterceptorRequest// set InterceptorRequest into request attribute, eg "InterceptorRequest"log.info("preHandle");String requestBody = HttpRequestContext.getRequestBody(request);log.info("Request Body: {}", requestBody);request.setAttribute(INTERNAL_REQUEST_BODY, requestBody);return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// get InterceptorRequest from request attribute "InterceptorRequest"// update response body, response code into InterceptorRequest// save into persistence systemlog.info("afterCompletion");String requestBody = (String) request.getAttribute(INTERNAL_REQUEST_BODY);log.info("Request Body: {}", requestBody);if (response instanceof ContentCachingResponseWrapper responseWrapper) {byte[] responseBody = responseWrapper.getContentAsByteArray();String responseBodyStr = new String(responseBody, response.getCharacterEncoding());log.info("Response Body: {}", responseBodyStr);// write response body to responseresponseWrapper.copyBodyToResponse();}request.removeAttribute(INTERNAL_REQUEST_BODY);}
}

logback-spring.xml

%X{requestId:-MISSING} 输出MDC requestId

<configuration><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %X{requestId:-MISSING} %logger{36} - %msg%n</pattern>        </encoder></appender><root level="info"><appender-ref ref="STDOUT" /></root>
</configuration>
http://www.dtcms.com/a/269177.html

相关文章:

  • [netty5: LifecycleTracer ResourceSupport]-源码分析
  • idea启动后闪一下,自动转为后台运行
  • 全国产化行业自主无人机智能处理单元-AI飞控+通信一体化模块SkyCore-I
  • VmWare 安装 mac 虚拟机
  • 量子计算+AI芯片:光子计算如何重构神经网络硬件生态
  • C++ 定位 New 表达式深度解析与实战教程
  • 如果让计算机理解人类语言- Word2Vec(Word to Vector,2013)
  • 系统学习Python——并发模型和异步编程:基础知识
  • 无需公网IP的文件交互:FileCodeBox容器化部署技术解析
  • AI编程才刚起步,对成熟的软件工程师并未带来质变
  • Java 内存分析工具 Arthas
  • Cookie的HttpOnly属性:作用、配置与前后端分工
  • 用U盘启动制作centos系统最常见报错,系统卡住无法继续问题(手把手)
  • 用于构建多模态情绪识别与推理(MERR)数据集的自动化工具
  • 2025年全国青少年信息素养大赛图形化(Scratch)编程小学高年级组初赛样题答案+解析
  • 【Netty高级】Netty的技术内幕
  • 设计模式—专栏简介
  • Baumer工业相机堡盟工业相机如何通过DeepOCR模型识别判断数值和字符串的范围和相似度(C#)
  • Spring AOP 设计解密:代理对象生成、拦截器链调度与注解适配全流程源码解析
  • 學習網頁製作
  • 应用俄文OCR技术,为跨语言交流与数字化管理提供更强大的支持
  • 【前端UI】【ShadCN UI】一个干净、语义化、可拓展、完全可控的“代码级组件模板库”
  • 选择排序算法详解(含Python实现)
  • python中MongoDB操作实践:查询文档、批量插入文档、更新文档、删除文档
  • 指尖上的魔法:优雅高效的Linux命令手册
  • GitHub 趋势日报 (2025年07月06日)
  • PyTorch 详细安装教程及核心API使用指南
  • Chatbox➕知识库➕Mcp = 机器学习私人语音助手
  • 分层Agent
  • turborepo 如何解决git管理包过大的问题