程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

使用 ContentCachingRequestWrapper 缓存 HttpServletRequest 对象后,如何读取请求正文?

发布于2022-10-31 22:00     阅读(1413)     评论(0)     点赞(13)     收藏(2)


如果发生一些自定义异常,我正在记录请求正文。为此,我添加了一个过滤器,它HttpServletRequest使用ContentCachingRequestWrapper. 这是代码示例:

@Component
public class RequestWrapperFilter extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse);
  }

}

而且,我的控制器类看起来像这样:
@PostMapping(Paths.INSPECTION_IMAGE_SUBMIT_REQUEST_V1)
  public ResponseEntity<ResponseObject> processThisRequest(
    @RequestBody RequestObject requestObject //how am I able to access this requestObject?
  ) throws Exception {
    return someService.process(requestBody);
  }

那么,我该如何使用它requestObject呢?因为,在过滤器类中,我已经缓存了这个,因此,这个getReader()方法一定已经被调用了,对吧?所以我应该无法阅读requestObject,对吧?


解决方案


======编辑======

看看ContentCachingRequestWrapper 效果如何

javax.servlet.http.HttpServletRequest 包装器缓存从输入流和阅读器读取的所有内容,并允许通过字节数组检索此内容。

缓存并不意味着它读取输入流并保存在内存中,但是每当从包装流中读取字节时,缓存器都会将相同的字节写入其内部缓冲区。

所以你requestObject在整个过滤器链中只被读取一次,当你ContentCachingRequestWrapper在你的过滤器中创建时,它还没有缓存任何东西。

框架的其他部分将通过调用该ContentCachingRequestWrapper#getContentAsByteArray方法来读取缓存的内容(不再从流中读取,因为它已经读取了)。(注意,只有body reader读完输入流后才能看到内容,如果之前调用,会收到不完整的数据)

======结束编辑======

可以使用RequestBodyAdviceAdapter


@ControllerAdvice
public class RequestAdvice extends RequestBodyAdviceAdapter {
    
    @Override
    @Nonnull
    public Object afterBodyRead(@Nonnull Object body, @Nonnull HttpInputMessage inputMessage,
        @Nonnull MethodParameter parameter, @Nonnull Type targetType,
        @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        
        // Do something with the payload
        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }
}


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/562805/dc7fa33e21609e73e42d/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)