简体   繁体   中英

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. When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the 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? 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
  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. That way it can be read muiltiple times.

spring's AbstractRequestLoggingFilter does something similar and has an example wrapper, you can check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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