Only reset response buffer for error handling

Prior to this commit, `DispatcherServlet` would completely reset the
response (status, headers and body) before handling errors within Spring
MVC. This can cause unintended consequences when Servlet Filters added
response headers before the error happened. Such response headers might
be still required in case of error handling.

This commit changes the complete reset of the response to only resetting
the response buffer, if possible.

Closes gh-31154
See gh-31104
This commit is contained in:
Brian Clozel
2023-09-08 18:47:21 +02:00
parent 88ee8fc92f
commit 0f945873a3
2 changed files with 61 additions and 57 deletions

View File

@@ -1338,9 +1338,10 @@ public class DispatcherServlet extends FrameworkServlet {
// Success and error responses may use different content types
request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
// Reset the response if the response is not committed already
// Reset the response body buffer if the response is not committed already,
// leaving the response headers in place.
try {
response.reset();
response.resetBuffer();
}
catch (IllegalStateException illegalStateException) {
// the response is already committed, leave it to exception handlers anyway