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

相关推荐
没有bug.的程序员7 分钟前
Istio 服务网格:流量治理内核、故障注入实战与云原生韧性架构深度指南
spring boot·云原生·架构·istio·流量治理·故障注入·韧性架构
李慕婉学姐23 分钟前
Springboot眼镜店管理系统ferchy1l(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
常利兵36 分钟前
Spring Boot 3 多数据源整合 Druid:监控页面与控制台 SQL 日志配置实战
android·spring boot·sql
qq_12498707531 小时前
基于Javaweb的《战舰世界》游戏百科信息系统(源码+论文+部署+安装)
java·vue.js·人工智能·spring boot·游戏·毕业设计·计算机毕业设计
独断万古他化1 小时前
【SSM开发实战:博客系统】(一)项目初始化与基础功能实现
spring boot·spring·mybatis·博客系统·项目
独自破碎E1 小时前
Spring Boot测试启动失败:SLF4J日志多实现冲突解决方案
spring boot·后端·log4j
计算机毕设指导61 小时前
基于微信小程序的校园二手交易系统【源码文末联系】
java·spring boot·spring·微信小程序·小程序·tomcat·maven
Code王1 小时前
【课程设计/毕业设计】基于springboot +微信小程序的家政服务平台系统基于小程序的家政服务系统安全开发【附源码、数据库、万字文档】
spring boot·小程序·课程设计
Coder_Boy_1 小时前
企业级项目高并发监控场景-Spring Boot 集成 Graphite & InfluxDB 实战文档
java·spring boot·后端·系统架构
计算机学姐13 小时前
基于SpringBoot的电影点评交流平台【协同过滤推荐算法+数据可视化统计】
java·vue.js·spring boot·spring·信息可视化·echarts·推荐算法