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

相关推荐
Tirzano5 小时前
SpringOAuth2Server 自定义授权码认证,登录和授权码混合
spring boot
一 乐6 小时前
饮食营养信息|基于springboot + vue饮食营养管理信息平台系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·饮食营养管理信息系统
Devin~Y7 小时前
大厂Java面试实战:Spring Boot/WebFlux、Redis+Kafka、K8s可观测性与Spring AI RAG/Agent三轮连环问
java·spring boot·redis·kafka·kubernetes·resilience4j·spring webflux
悟空码字7 小时前
别再重复造轮子了!SpringBoot对接第三方系统模板,拿来即用
java·spring boot·后端
indexsunny7 小时前
互联网大厂Java求职面试实战:Spring Boot与微服务架构解析
java·spring boot·redis·kafka·spring security·flyway·microservices
我叫张土豆7 小时前
让 AI 学会用工具:基于 LangChain4j 的 Skills Agent 全栈落地实战
人工智能·spring boot
我登哥MVP7 小时前
【SpringMVC笔记】 - 2 - @RequestMapping
java·spring boot·spring·servlet·tomcat·intellij-idea·springmvc
常利兵8 小时前
从0到1:Spring Boot 中WebSocket实战揭秘,开启实时通信新时代
spring boot·后端·websocket
希望永不加班9 小时前
SpringBoot 依赖管理:BOM 与版本控制
java·spring boot·后端·spring
勿忘,瞬间9 小时前
Spring Boot
java·数据库·spring boot