Lazily Check the Body of an HttpServletRequest

This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

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:

  1. If the body never happens to be read (i.e. neither the getInputStream or getReader methods get called) then it will never be examined.
  2. If the request gets unwrapped (via the getRequest method of ServletRequestWrapper inherited by my custom HttpServletRequest class) then my overrided method will not be called.

Leave a Reply

Note that comments won't appear until approved.