Skip to content

Commit ccf4b02

Browse files
committed
Fix null value support in ContentCachingResponseWrapper
Prior to this commit, calling `setHeader` on the response wrapper would have a separate code path for the "Content-Length" header. This did not support calls with `null` values and would result in an exception. This commit ensures that the cached content length value is reset in this case and that the call is forwarded properly to the superclass. Fixes gh-34465
1 parent b5c89c9 commit ccf4b02

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

spring-web/src/main/java/org/springframework/web/util/ContentCachingResponseWrapper.java

+7-1
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,13 @@ public boolean containsHeader(String name) {
164164
@Override
165165
public void setHeader(String name, String value) {
166166
if (HttpHeaders.CONTENT_LENGTH.equalsIgnoreCase(name)) {
167-
this.contentLength = toContentLengthInt(Long.parseLong(value));
167+
if (value != null) {
168+
this.contentLength = toContentLengthInt(Long.parseLong(value));
169+
}
170+
else {
171+
this.contentLength = null;
172+
super.setHeader(name, null);
173+
}
168174
}
169175
else {
170176
super.setHeader(name, value);

spring-web/src/test/java/org/springframework/web/filter/ContentCachingResponseWrapperTests.java

+11
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,17 @@ void setContentLengthAbove2GbViaSetHeader() {
270270
.withMessageContaining(overflow);
271271
}
272272

273+
@Test
274+
void setContentLengthNull() {
275+
MockHttpServletResponse response = new MockHttpServletResponse();
276+
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
277+
responseWrapper.setContentLength(1024);
278+
responseWrapper.setHeader(CONTENT_LENGTH, null);
279+
280+
assertThat(response.getHeaderNames()).doesNotContain(CONTENT_LENGTH);
281+
assertThat(responseWrapper.getHeader(CONTENT_LENGTH)).isNull();
282+
}
283+
273284

274285
private void assertHeader(HttpServletResponse response, String header, int value) {
275286
assertHeader(response, header, Integer.toString(value));

0 commit comments

Comments
 (0)