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

相关推荐
Mr.朱鹏6 分钟前
超时订单处理方案实战指南【完整版】
java·spring boot·redis·spring·rabbitmq·rocketmq·订单
Coder_Boy_23 分钟前
SpringAI与LangChain4j的智能应用-(实践篇4)
java·人工智能·spring boot·langchain
用户3521802454751 小时前
🎉Spring Boot 3 + 多数据源 + Druid:监控页面 + 控制台 SQL 日志,终于搞定啦!
spring boot·微服务
while(1){yan}1 小时前
计算器和登录界面(实现前后端互通)
spring boot·spring·servlet·java-ee·tomcat·maven
xiaoshujiaa2 小时前
Java大厂面试实录:谢飞机硬刚互联网医疗微服务架构,Spring Cloud+Redis+Kafka全踩坑
spring boot·redis·微服务·kafka·flyway·java面试·互联网医疗
一 乐2 小时前
养老院信息|基于springboot + vue养老院信息管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
天远Date Lab2 小时前
构建金融级信贷审批系统:Java Spring Boot 集成天远借贷行为验证 API 全指南
java·大数据·spring boot·金融
爱吃山竹的大肚肚3 小时前
Spring Boot 与 Apache POI 实现复杂嵌套结构 Excel 导出
java·spring boot·后端·spring·spring cloud·excel
高级盘丝洞3 小时前
Spring Boot 集成 InfluxDB 3.x
spring boot
宋情写4 小时前
Springboot基础篇01-创建一个SpringBoot项目
java·spring boot·后端