Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A filter logs the request body by reading request.getInputStream(), and then the controller fails with an empty body. Why, and how do you fix it?

The request body arrives as a stream from the network, and request.getInputStream() can be read only once: after the filter reads it to the end, nothing is left, so the controller's message converter finds an empty body. We fix it by wrapping the request so the body is cached, for example with Spring's ContentCachingRequestWrapper, passing the wrapper down the chain and reading the cached content after the chain has run, or by writing our own wrapper that reads the body into memory once and returns a fresh stream on every call. Either way we limit the size, skip large or binary bodies, and never log sensitive fields.

Why this question is asked

Logging request bodies is a very natural thing to want when debugging an API, and the first attempt nearly always breaks the API it is meant to observe. Interviewers ask about this because the fix requires understanding how the Servlet API exposes the body, how request wrappers work, and the memory and privacy costs of keeping a body around. In this answer, we will recap how the body is read, reproduce the empty body, look at the two fixes with code, and then cover the limits a safe logging filter needs.

1A Quick Recap: The Body Is a Stream

When a client sends a POST with a JSON body, the container reads the headers and hands the application an HttpServletRequest. The body is not loaded into memory; it stays in the connection, and request.getInputStream() returns a ServletInputStream that reads it from the network as we consume it. That keeps memory use low even for large uploads.

A stream is consumed as it is read. Once we have read all the bytes, the stream is at its end and there is no way to rewind it. Calling getInputStream() again returns the same, already-finished stream. The servlet specification also says we may use either getInputStream() or getReader() for a request, not both.

2Reproducing the Empty Body

Here is the filter that causes the problem, followed by what the controller sees.

Java
@Component
class BodyLogFilter extends OncePerRequestFilter {
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String body = new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
log.info("body: {}", body); // body: {"item":"book","qty":2}
chain.doFilter(req, res);
}
}
@PostMapping("/orders")
Order create(@RequestBody OrderRequest r) { ... }
// 400 Bad Request: HttpMessageNotReadableException: Required request body is missing
Step throughTwo readers, one stream
ClientBodyLogFilterMessage converter
POST /orders with 32-byte JSON body
readAllBytes(): 32 bytes, stream now at end
chain.doFilter(req, res)
read(): -1, nothing left
400 Required request body is missing

5 messages in order. Play them, or step through them one at a time.

The filter read every byte, so the stream is at its end. When the controller's Jackson message converter reads the same stream, it gets nothing, and Spring reports a missing body. The log line shows the body, which makes the bug confusing at first: the data clearly arrived.

3Fix 1: Spring's ContentCachingRequestWrapper

A request wrapper is a class that extends HttpServletRequestWrapper, delegating everything to the original request but overriding the methods it wants to change. We pass the wrapper down the chain instead of the original, so everyone after us uses it.

ContentCachingRequestWrapper wraps the input stream so that every byte the controller reads is also copied into an in-memory buffer. It does not read ahead; it records what is consumed. So the controller reads the body normally, and after the chain returns we read the copy with getContentAsByteArray().

Java
@Component
class BodyLogFilter extends OncePerRequestFilter {
private static final int LIMIT = 10_000; // cache at most 10 KB
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
ContentCachingRequestWrapper wrapped = new ContentCachingRequestWrapper(req, LIMIT);
try {
chain.doFilter(wrapped, res); // the controller reads the body normally
} finally {
byte[] body = wrapped.getContentAsByteArray();
log.info("POST {} body: {}", req.getRequestURI(), new String(body, StandardCharsets.UTF_8));
// POST /orders body: {"item":"book","qty":2}
}
}
}

Notice that we read the cached content after the chain, not before. Before the chain, the cache is empty, because nothing has been read yet. A consequence is that if the controller never reads the body, for example because security rejects the request first, there is nothing to log. The wrapper also handles form posts, where the body is consumed by getParameter. Check the constructors your Spring version offers; the one with a cache limit is the safer choice.

4Fix 2: A Wrapper That Reads the Body Up Front

If we need the body before the controller runs, for example to verify a signature over it, we read it fully into memory once and give every caller a fresh stream over those bytes.

Java
class CachedBodyRequest extends HttpServletRequestWrapper {
private final byte[] body;
CachedBodyRequest(HttpServletRequest req, int limit) throws IOException {
super(req);
byte[] data = req.getInputStream().readNBytes(limit + 1);
if (data.length > limit) throw new PayloadTooLargeException(limit); // our own exception -> 413
this.body = data;
}
byte[] body() { return body; }
@Override public ServletInputStream getInputStream() {
ByteArrayInputStream in = new ByteArrayInputStream(body); // new stream on every call
return new ServletInputStream() {
@Override public int read() { return in.read(); }
@Override public boolean isFinished() { return in.available() == 0; }
@Override public boolean isReady() { return true; }
@Override public void setReadListener(ReadListener l) { throw new UnsupportedOperationException(); }
};
}
@Override public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
}
}
// filter: var cached = new CachedBodyRequest(req, 10_000); verify(cached.body()); chain.doFilter(cached, res);

Notice the limit. readNBytes(limit + 1) reads at most one byte more than allowed, which is enough to know whether the body is too big without reading a huge upload into memory. For simplicity this sketch decodes as UTF-8; a full version would use the request's declared character encoding.

5Memory, Size and Sensitive Data

Both fixes keep the body in memory for the length of the request. With 200 concurrent requests of 1 MB each, that is 200 MB of heap just for logging copies, so we cap the cached size, skip multipart uploads and binary content types entirely, and usually log only for specific paths or at debug level.

Bodies also contain data we must not write to logs: passwords, card numbers, tokens, personal details. Logs are copied to many systems and kept for a long time. So a body logging filter either masks known sensitive fields, for example by parsing JSON and replacing values of keys like password or cardNumber, or logs only metadata such as size and content type in production. Spring also ships AbstractRequestLoggingFilter and CommonsRequestLoggingFilter, which can include a truncated payload; the same cautions apply.

6Follow-up questions

Why does reading parameters sometimes empty the body too?

For a form post with content type application/x-www-form-urlencoded, the container parses the body to provide request parameters. The first call to getParameter reads the body stream, and after that getInputStream returns nothing. The reverse is also true: if a filter reads the stream first, getParameter finds no form data. ContentCachingRequestWrapper handles this case by caching the parameters when they are read.

How do we log the response body?

With ContentCachingResponseWrapper. We pass it down the chain, read getContentAsByteArray() afterwards, and then must call copyBodyToResponse(), because the wrapper holds the body in memory and the client receives nothing until it is copied to the real response. The same size and privacy cautions apply.

Does this work for streaming or reactive endpoints?

Not well. Caching defeats streaming by holding the data in memory, and WebFlux applications do not use the Servlet API at all; there the body is a Flux of buffers and logging is done with a WebFilter that decorates the request, with the same limits.

7Conclusion

In this answer, we saw that the request body is a stream that can be read only once, so a filter that reads it leaves an empty body for the controller. We fixed it with ContentCachingRequestWrapper, which copies the bytes as the controller reads them so we log the cached content after the chain, or with our own wrapper that reads the body into memory once with a size limit and returns a new stream on each call. We also capped the size, skipped large and binary bodies, and masked sensitive fields.

What to say in the interviewAbout 100 seconds aloud

Open with

The body is exposed as a ServletInputStream that reads from the connection, and a stream can be consumed only once. My filter read all the bytes to log them, so when the chain continued and Jackson's message converter tried to read the body for @RequestBody, the stream was already at the end, and Spring reported that the required request body is missing.

Then, if they want more

The log line looked fine, which is what makes it confusing. The fix is to wrap the request so the body is cached, and pass the wrapper down the chain. The simplest option is Spring's ContentCachingRequestWrapper, ideally with a cache limit.

It copies bytes into a buffer as the controller reads them, so the controller works normally, and I read getContentAsByteArray after chain.doFilter returns, in a finally block. Reading it before the chain gives an empty array, because nothing has been read yet.

If I need the body before the controller, for example to check a signature, I write my own HttpServletRequestWrapper that reads the body into a byte array once, with a size limit, and returns a new ServletInputStream over that array on every getInputStream call, plus a matching getReader.

In both cases I watch memory: I cap the size, skip multipart and binary content, and only log where it is useful. And I never log sensitive data, so I mask fields like passwords and card numbers or log only metadata in production. For response bodies the equivalent is ContentCachingResponseWrapper, remembering to call copyBodyToResponse.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A filter logs the request body by reading request.getInputStream(), and then the...": https://scrivio-interview-library.netlify.app/java/servlets/26d1e9624b/