springboot请求入参重复读问题ContentCachingRequestWrapper

  • jakarta.servlet.http.HttpServletRequestWrapper

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

  • org.springframework.web.util.ContentCachingRequestWrapper

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

java 复制代码
@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

相关推荐
小咕聊编程19 分钟前
【含文档+PPT+源码】基于小程序的智能停车管理系统设计与开发
java·spring boot·小程序
命运之手3 小时前
[ Spring ] Spring Boot Mybatis++ 2025
spring boot·spring·mybatis·mybatis-plus·mybatis++
计算机-秋大田4 小时前
基于微信小程序的实习记录系统设计与实现(LW+源码+讲解)
vue.js·spring boot·后端·微信小程序·小程序·课程设计
飞翔的佩奇4 小时前
Java项目: 基于SpringBoot+mybatis+maven+mysql实现的疾病防控综合管理系统(含源码+数据库+毕业论文)
java·数据库·spring boot·mysql·spring·毕业设计·疾病防控
栗豆包5 小时前
w187社区养老服务平台的设计与实现
java·spring boot·后端·spring·tomcat
violin-wang5 小时前
如何在Intellij IDEA中识别一个文件夹下的多个Maven module?
java·spring boot·spring·maven·intellij-idea
星如雨グッ!(๑•̀ㅂ•́)و✧6 小时前
Spring Boot 2 快速教程:WebFlux处理流程(五)
java·spring boot·后端
小咕聊编程6 小时前
【Java源码】基于SpringBoot+小程序的电影购票选座系统
java·spring boot·小程序
冬天vs不冷6 小时前
SpringBoot源码解析(九):Bean定义接口体系
java·spring boot·rpc
阿乾之铭6 小时前
Spring Boot框架下的单元测试
spring boot·后端·单元测试