Quick revision
The short answer
For @ResponseBody and @RestController methods, the message converter writes the body while the handler is being processed, and it flushes the output, which commits the response before postHandle runs. Once a response is committed, its status and headers have already been sent, so response.setHeader() in postHandle is silently ignored. We add the header in preHandle, in a filter, or in a ResponseBodyAdvice; postHandle is mainly useful for adjusting the model before a view is rendered.
What to remember
In this answer, we saw that headers added in postHandle disappear for @RestController methods because the message converter writes and flushes the body inside the handler call, committing the response before postHandle runs, and the servlet API silently ignores later header changes. postHandle is meant for view-based handlers, where rendering comes later. The fixes are to set the header in preHandle, in a filter (with a response wrapper if it depends on the outcome), or in a ResponseBodyAdvice, or with ResponseEntity for a single endpoint.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For @ResponseBody and @RestController methods, the message converter writes the body while the handler is being processed, and it flushes the output, which commits the response before postHandle runs. Once a response is committed, its status and headers have already been sent, so response.setHeader() in postHandle is silently ignored. We add the header in preHandle, in a filter, or in a ResponseBodyAdvice; postHandle is mainly useful for adjusting the model before a view is rendered.
Why this question is asked
This bug is a classic because nothing fails: no exception, no warning, the interceptor runs, and the header simply is not there. It works for old server-rendered pages and fails for every JSON endpoint, which makes it look random. Interviewers ask it because the answer requires knowing exactly when Spring MVC writes a response. In this answer, we will reproduce the problem, recap what a committed response is, follow the order of events inside DispatcherServlet to see why postHandle is too late, and go through three fixes and when each one fits.
1Reproducing the Problem
Here is the interceptor and a controller. The interceptor tries to add a header once the handler has run.
The log line gives the game away. By the time postHandle runs, the response is already committed. The same interceptor on a @Controller method that returns a view name does add the header, which is why the behaviour seems inconsistent.
2A Quick Recap of Committed Responses
An HTTP response starts with a status line and headers, followed by the body. The servlet container buffers what we write, and the moment it sends the first bytes to the client, the response is committed. That happens when the buffer fills up or when someone flushes the output stream.
After commit, the status and headers are on the wire and cannot be changed. The servlet API does not throw if we try; setHeader() and addHeader() on a committed response are simply ignored. That silence is why this bug is hard to spot.
3Why postHandle Is Too Late
Inside DispatcherServlet, the order of events is: run preHandle on each interceptor, let the handler adapter invoke the controller method and process its return value, run postHandle, render the view if there is one, and finally run afterCompletion.
The key part is "process its return value". For a @ResponseBody method, the return value handler is RequestResponseBodyMethodProcessor, and it writes the Order to the response immediately using the Jackson converter. The converter writes the JSON and flushes the output stream, which commits the response. So by the time the adapter returns and DispatcherServlet calls postHandle, the client may already have the headers. There is no ModelAndView to render; the mav parameter is null.
For a view-based controller the story is different. The method returns "orders/list", nothing is written yet, and the view is rendered after postHandle. That is what postHandle was designed for: changing the model or the view before rendering.
7 messages in order. Play them, or step through them one at a time.
For @ResponseBody, the body is written inside handle(), before postHandle.
4Fix 1: Add the Header in preHandle
If the header does not depend on the result, the simplest fix is to set it before the handler runs.
This keeps the interceptor, which is useful when the header depends on the handler, for example a version read from an annotation on the controller method.
5Fix 2: Use a Filter
If the header applies to every response and needs no handler information, a filter is a natural home. A filter can set the header before calling chain.doFilter(). If it must set a header based on the outcome, such as timing information, it can wrap the response in a ContentCachingResponseWrapper, which holds the body in memory until the filter calls copyBodyToResponse(); the response is then not committed until the filter decides.
The cost is memory: every body is held in full before sending, so this suits small JSON responses, not file downloads or streams.
6Fix 3: Use a ResponseBodyAdvice
A ResponseBodyAdvice runs inside the return value processing, after the converter is chosen but before it writes. Its beforeBodyWrite method receives the ServerHttpResponse, and headers set there are still sent. This is the best choice when the header depends on the body or on the controller, and it only applies to @ResponseBody and ResponseEntity responses, which is exactly where postHandle failed.
A fourth option for a single endpoint is to return ResponseEntity.ok().header("X-Api-Version", "2").body(order), which puts the header next to the code that knows about it.
7Follow-up questions
Would afterCompletion work instead?
No, it runs even later, after the response is complete. afterCompletion is meant for clean-up and for recording the outcome, such as logging the status or releasing resources, not for changing the response.
Can a large view-rendered page hit the same problem?
Not in postHandle, because rendering happens after it. But code that tries to set headers after rendering, or a view that writes more than the buffer size and triggers an automatic flush, can hit the same committed-response rule. The general rule is that headers must be set before the first bytes of the body are sent.
How would you catch this kind of bug in tests?
Assert on headers in a MockMvc test, for example andExpect(header().string("X-Api-Version", "2")), for at least one @RestController endpoint. The most reliable version runs against the real embedded server with @SpringBootTest(webEnvironment = RANDOM_PORT) and an HTTP client, because the real container enforces the committed state; MockMvc's mock response may behave slightly differently, so check your version before relying on it alone.
8Conclusion
In this answer, we saw that headers added in postHandle disappear for @RestController methods because the message converter writes and flushes the body inside the handler call, committing the response before postHandle runs, and the servlet API silently ignores later header changes. postHandle is meant for view-based handlers, where rendering comes later. The fixes are to set the header in preHandle, in a filter (with a response wrapper if it depends on the outcome), or in a ResponseBodyAdvice, or with ResponseEntity for a single endpoint.
Open with
The reason is timing. For a @ResponseBody method, the return value is handled by RequestResponseBodyMethodProcessor while the handler adapter is still running. It picks the Jackson converter, writes the JSON and flushes the stream, and that flush commits the response, meaning status and headers have been sent.
Then, if they want more
DispatcherServlet only calls postHandle after the adapter returns, and by then setHeader is silently ignored. You can see it if you log response.isCommitted() in postHandle: it's true. The same interceptor works on a classic @Controller that returns a view name, because there nothing is written until the view renders after postHandle.
That's really what postHandle is for, adjusting the model or view before rendering. To fix it, if the header doesn't depend on the result, I'd just set it in preHandle.
If it applies to every request, a filter that sets it before chain.doFilter is simplest, and if it depends on the outcome, the filter can use a ContentCachingResponseWrapper, at the cost of buffering the body.
If it depends on the body or the controller and only matters for REST responses, a ResponseBodyAdvice is the right hook, because beforeBodyWrite runs before the converter writes and gets the ServerHttpResponse. For a single endpoint, ResponseEntity with the header is clearest. And I'd add a MockMvc test asserting the header so it can't regress silently.
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
- Spring Framework reference, Spring Web MVC
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 HandlerInterceptor adds a response header in postHandle, but the header never appears...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/ec65d6544c/