You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何ContentCachingResponseWrapper需调用chain.doFilter()才能获取缓存内容?

关于ContentCachingResponseWrapper必须调用chain.doFilter()才能获取内容的原因

核心逻辑拆解

  • ContentCachingResponseWrapper只是"缓存容器",而非"内容生成器"
    它的作用是拦截并缓存后续流程写入响应的字节数据,但本身不会凭空生成响应内容。刚创建实例时,内部缓存数组是空的,没有任何数据。

  • chain.doFilter()是触发响应内容生成的关键
    这个方法会把请求传递到过滤器链的下一环,最终到达处理请求的核心组件(比如Controller或Servlet)。只有这些组件执行后,才会生成响应内容并写入响应流——此时ContentCachingResponseWrapper会把写入的字节缓存起来,你才能通过getContentAsByteArray()拿到有效数据。

  • 哪怕没有自定义过滤器,也不能跳过chain.doFilter()
    就算你没配置其他自定义过滤器,Servlet容器或Spring框架本身也有默认的处理流程。跳过这个方法等于直接终止了请求处理,没有任何代码会生成响应内容,缓存自然是空的。

你的示例代码回顾

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    System.out.println("In ServletFilter");
    HttpServletResponse res = (HttpServletResponse) response;
    ContentCachingResponseWrapper ccrw = new ContentCachingResponseWrapper(res);
    
    chain.doFilter(request, ccrw); // 不执行这句,后续流程不会生成响应内容

    String content = new String(ccrw.getContentAsByteArray(), "UTF-8");
    System.out.println(content);   // 自然拿不到内容
}

内容的提问来源于stack exchange,提问作者Om Shreenidhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:25:51