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

相关推荐
摇滚侠6 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 32
spring boot·笔记·后端
卓怡学长14 小时前
w210基于springboot反诈平台设计与实现
java·spring boot·spring·intellij-idea
大模型丫丫15 小时前
如何提升单体 Spring Boot 应用的并发数?
java·spring boot·后端
RuoyiOffice15 小时前
SpringBoot3+Vue3 最推荐的开源 OA 系统 2026:流程驱动、资源闭环、多端互通
spring boot·vue3·flowable·oa·协同办公·spring boot 3·开源oa
计算机毕设定制辅导-无忧学长16 小时前
基于Spring Boot的玄幻小说个性化推荐平台设计与实现
java·vue.js·spring boot·后端·mysql·推荐算法
Harry Lei16 小时前
长期记忆系统的设计与实现
spring boot·postgresql·embedding
卓怡学长18 小时前
w156一周穿搭App的设计与实现
java·spring boot·spring·maven·intellij-idea
步行cgn19 小时前
Spring Boot 绑定简单 Bean 详解
java·spring boot·后端
爱折腾的编程老炮20 小时前
潮玩品牌自建抽盒机小程序——商城 + 抽盒 + 一番赏 + 会员 + 社区,一套代码怎么搭
spring boot·小程序·vue·mybatis·uniapp
谢亮_vipxieliang21 小时前
ValidX vs Google Guava Preconditions:验证 vs 断言
java·spring boot·后端·spring cloud·hibernate·guava