Issue
I was facing this issue, where I was reading the request using javax.servlet.http.HttpServletRequest.getReader()
and it was clearing the request after that. So when I was passing it forward in the filter chain, it was passing request as null
I was able to resolve this by following similar solution:
How can I read request body multiple times in Spring 'HandlerMethodArgumentResolver'?
My question is why are we not allowed to read the request multiple times?
Solution
Why can the body of the HttpServletRequest not be read multiple times?
Because that would require the servlet stack to buffer the entire request body ... in case the servlet decides to re-read it. That is going to be a performance and/or memory utilization hit for all requests. And it won't work unless there is enough memory to buffer multiple instances (for multiple simultaneous requests) of the largest anticipated request body.
Note that there is no way to get the client to resend the data, short of failing the HTTP request. Even then, the client may not be able to resend it ... because it may not have been able to buffer the data itself.
In short: rereading the request body is not supported by the servlet APIs because it doesn't scale. If a servlet wants to reread the data, it needs to buffer it itself.
Answered By - Stephen C
Answer Checked By - David Marino (JavaFixing Volunteer)