Video in progress
You logged the request body in a filter and now the controller gets an empty body. How would you fix it using a decorator?
An InputStream can be read only once. You wrap the request with HttpServletRequestWrapper to build a decorator that keeps the body in memory, or you use Spring's ContentCachingRequestWrapper.
📖 Answer
A decorator is a wrapper with the same interface as the original object. It changes some methods and passes the rest through to the original. Java I/O is built entirely on this: new BufferedReader(new InputStreamReader(socket.getInputStream())). The Servlet API has a ready-made HttpServletRequestWrapper for it.
Spring's ready-made version:
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
var wrapped = new ContentCachingRequestWrapper(req, 64 * 1024);
chain.doFilter(wrapped, res);
// the body is in the cache only after the controller has finished reading it
log.debug("body={}", new String(wrapped.getContentAsByteArray(), StandardCharsets.UTF_8));
}
There is a catch: ContentCachingRequestWrapper doesn't read the body ahead of time. It only copies what someone else has read. So if you want to see the body before chain.doFilter, it is empty. If you need it earlier (for example to verify a signature), you write your own wrapper: read the body into a byte[] and return getInputStream()/getReader() from that array.
What not to forget on prod is a limit. On an endpoint that accepts 200 MB file uploads, pulling the body into memory eats the heap. Exclude multipart and large endpoints from this filter, and mask passwords and card numbers in the logs.
Sign up to mark studied questions and save your progress.