Skip to content

Copy headers and cookies in ServerResponse builders - #37637

Open
lejuho wants to merge 1 commit into
spring-projects:mainfrom
lejuho:server-response-builder-copy
Open

lejuho wants to merge 1 commit into
spring-projects:mainfrom
lejuho:server-response-builder-copy

Conversation

@lejuho

@lejuho lejuho commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

The functional ServerResponse builders in WebMvc and WebFlux hand their live HttpHeaders to the built response, which only wraps them with HttpHeaders.readOnlyHttpHeaders(...), and the cookies are copied with new LinkedMultiValueMap<>(cookies), which shares the value lists. As a result, calling header(...) or cookie(...) on a builder after build() changes a response that was already built, even though the response exposes its headers and cookies as read-only:

ServerResponse.BodyBuilder builder = ServerResponse.ok().header("foo", "bar");
ServerResponse response = builder.build();
builder.header("foo", "baz");
response.headers().get("foo"); // [bar, baz]

This PR copies the headers (HttpHeaders.copyOf) and the cookie value lists when the response is created, in both spring-webmvc (AbstractServerResponse) and spring-webflux (DefaultServerResponseBuilder.AbstractServerResponse). This follows the same builder-after-build isolation as #37596 (RetryPolicy.Builder) and #37601 (HttpServiceProxyFactory.Builder); #37604 proposes the same for Rendering builders.

A test is added to DefaultServerResponseBuilderTests in each module; it fails before the change and passes after it.

The functional ServerResponse builders in WebMvc and WebFlux passed
their live HttpHeaders to the built response, which only wrapped them
read-only, and copied the cookies map while sharing its value lists.
Calling header() or cookie() on a builder after build() therefore
changed a response that had already been built.

This commit copies the headers and the cookie value lists when the
response is created, in line with the builder changes for
RetryPolicy.Builder and HttpServiceProxyFactory.Builder.

See spring-projectsgh-37596
See spring-projectsgh-37601

Signed-off-by: lejuho <zedd1324@gmail.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Nov 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged or decided on

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants