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

相关推荐
凤山老林2 小时前
高保真集成测试:Spring Boot 结合 Testcontainers 的工程落地
spring boot·后端·集成测试
RuoyiOffice2 小时前
SpringBoot3+Vue3 接口访问日志实战:@ApiAccessLog 慢接口、参数脱敏与 OperateLog 如何分工
spring boot·vue3·traceid·spring boot 3·访问日志·apiaccesslog·操作日志
counting money3 小时前
SpringBoot 项目创建(IDEA不全,还需要修改)
java·spring boot·spring·maven
阿部多瑞 ABU3 小时前
从0到1:用 Spring Boot 3.4 + Vue3 做一个能“智能排道次“的运动会编排系统(附核心算法)
java·spring boot·后端·算法·spring
MacroZheng3 小时前
几行代码给项目集成AI功能,Spring AI 2.0太香了!
java·人工智能·spring boot
元界metalite3 小时前
SpringBoot修改接口全字段更新为什么危险-MetaLite如何只更新变化字段
spring boot
Devin~Y4 小时前
从内容社区到AI智能客服:Spring Boot + Spring Cloud + Spring AI 全栈实战面试拆解
java·spring boot·redis·elasticsearch·spring cloud·kafka·mybatis
2602_959960924 小时前
电商大厂Java面试:从Spring Boot、JPA、微服务到Redis、Kafka、Spring Security与监控,谢飞机的爆笑三轮问答
java·jvm·spring boot·redis·面试题
码农进化录4 小时前
Java 程序员的 AI 进化论 | Spring Boot 搭企业智能客服,从设计到上线
java·spring boot·openai
旺仔学长 哈哈4 小时前
别只做车辆 CRUD:Spring Boot 共享汽车管理系统从预约到还车的完整实现---源码53766
java·spring boot·在线预约·共享汽车