Lazily Check the Body of an HttpServletRequest
Recently I was helping a junior developer analyze the incoming parameters of an HTTP request in a Spring/Java Servlet application.
The issue came down to reading the body of the request: the way an HttpServletRequest is designed, once the body is read, then the body is consumed. It’s gone. Any attempt to read the body again will result in reading an empty body.
Of course, that’s no good.
After a few attempts at caching the body to read it twice (either using custom wrappers or Spring’s ContentCachingRequestWrapper) I decided it might be better to lazily read the body. That is, only read the body when it’s requested, and then pass the body onto the requesting method.
I did this by creating a custom HttpServletRequest class (that extends HttpServletRequestWrapper).
And then, in a filter class, wrap the request and send in on down the chain
Finally, you’ll need to add the filter to your web.xml file:
There are two caveats, though:
- If the body never happens to be read (i.e. neither the
getReadermethods get called) then it will never be examined.
- If the request gets unwrapped (via the
ServletRequestWrapperinherited by my custom HttpServletRequest class) then my overrided method will not be called.