简体   繁体   English

Spring:如何在读取inputStream后使用@RequestBody

[英]Spring: How to use @RequestBody after reading inputStream

I'm having the issue described here but it's not clear to me how to address it. 我有这里描述的问题但我不清楚如何解决它。

The issue is that I have an AuthenticationProvider which has to read the body of the request. 问题是我有一个AuthenticationProvider,它必须读取请求的主体。 When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the inputStream. 但是,当我的控制器方法想通过@RequestMapping使用该数据时,它是空的,因为Provider已经读取了inputStream。

Is there a way to obtain an inputReader from Request which supports mark/reset so my provider can simply roll the stream back to it's initial state after it does the authentication? 有没有办法从Request获取一个支持标记/重置的inputReader,这样我的提供者可以在进行身份验证后简单地将流回滚到它的初始状态? It seems crazy that the default behavior of the filter is destructive modification of the request object. 看起来很疯狂,过滤器的默认行为是对请求对象的破坏性修改。

The Provider should be triggered only in specific cases, so it shouldn't affect your whole application. 应仅在特定情况下触发提供程序,因此不应影响整个应用程序。 But if you need the body in the requests handled by the provider, then you still have a workaround: 但是,如果您需要提供者处理的请求中的正文,那么您仍然有一个解决方法:

  1. implement a servlet Filter 实现一个servlet Filter
  2. wrap the request 包装请求
  3. in the wrapper cache the request body, and then override the getInputStream() method to return a ByteArrayInputStream with the cached request body. 在包装器中缓存请求主体,然后重写getInputStream()方法以返回带有缓存请求主体的ByteArrayInputStream That way it can be read muiltiple times. 这样它可以多次读取。

spring's AbstractRequestLoggingFilter does something similar and has an example wrapper, you can check it. spring的AbstractRequestLoggingFilter执行类似的操作,并有一个示例包装器,您可以检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM