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

springboot请求入参重复读问题ContentCachingRequestWrapper

  • jakarta.servlet.http.HttpServletRequestWrapper

此类是HttpServletRequest的子类,提供了HttpServletRequest接口的边界实现,开发人员可以根据自己的需要实现此包装类的具体方法。

  • org.springframework.web.util.ContentCachingRequestWrapper

ContentCachingRequestWrapper是spring对HttpServletRequest的实现,用于解决请求内容不可以重复读取问题;其用于缓存所有从input stream和reader读取的内容,并且允许这些内容通过字节数组存储;此类扮演了拦截器的角色来缓存请求内容,如果请求内容没有被消费,则请求内容将不会被缓存,并且通过getContentAsByteArray()获取不到请求内容;

@Component
public class RequestWrapperFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //创建ContentCachingRequestWrapper对象用于缓存请求体
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        //创建ContentCachingResponseWrapper对象用于缓存响应体
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        //继续执行过滤器链,并传递包装后的请求对象
        filterChain.doFilter(requestWrapper, responseWrapper);
        //过滤器链执行完毕,请求体被消费 读取缓存的请求体
        byte[] reqBody = requestWrapper.getContentAsByteArray();
        //将请求体转换为字符串
        String reqBodyStr = new String(reqBody, requestWrapper.getCharacterEncoding());
        //打印请求体
        System.out.println("Request Param:" + reqBodyStr);

        //----------------response----------------
        //过滤器执行完毕,读取响应体
        byte[] resBody = responseWrapper.getContentAsByteArray();
        //将响应体转换为字符串
        String resBodyStr = new String(resBody, responseWrapper.getCharacterEncoding());
        //打印响应体信息
        System.out.println("Response Body:" + resBodyStr);
        //将缓存的响应体数据回写到响应流中
        responseWrapper.copyBodyToResponse();
    }
}

ContentCachingResponseWrapper是读响应数据进行缓存

开源SDK:https://github.com/mingyang66/spring-parent


http://www.kler.cn/a/421838.html

相关文章:

  • 第四十四篇 EfficientNetV1、V2模型详解
  • 【机器学习】探索机器学习决策树算法的奥秘
  • 初识ProtoBuf以及环境搭建(Win和Ubuntu)
  • Qt自定义 Widget 组件
  • Leetcode热题100-287 寻找重复数
  • lua-cjson 例子
  • 批量生成不同用户的pdf 文件(html样式)
  • 【C++进阶篇】C++继承进阶:深入理解继承的复杂性
  • 基础入门-Web应用OSS存储负载均衡CDN加速反向代理WAF防护部署影响
  • Recaptcha2 图像识别 API 对接说明
  • flask的第一个应用
  • 设计模式——方法链or流式接口
  • 什么是 Kubernetes(K8s)?
  • Chapter 17 v-model进阶
  • 深入探讨锁升级问题
  • 基于Java Springboot智慧农业微信小程序
  • 0.Git初步概念
  • 【Linux】设计文件系统(C实现)
  • 【C#】书籍信息的添加、修改、查询、删除
  • C++创建动态链接库(附原因说明)