Skip to content

Commit 7493ce8

Browse files
committed
Fix ServletResponseHttpHeaders#get null handling
ServletResponseHttpHeaders#get should be annotated with `@Nullable` and return null instead of a singleton list containing null when there is no content type header. Closes gh-32362
1 parent ce9dc19 commit 7493ce8

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

spring-web/src/main/java/org/springframework/http/server/ServletServerHttpResponse.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -171,13 +171,15 @@ public String getFirst(String headerName) {
171171
}
172172

173173
@Override
174+
@Nullable
174175
public List<String> get(Object key) {
175176
Assert.isInstanceOf(String.class, key, "Key must be a String-based header name");
176177

177178
String headerName = (String) key;
178179
if (headerName.equalsIgnoreCase(CONTENT_TYPE)) {
179180
// Content-Type is written as an override so don't merge
180-
return Collections.singletonList(getFirst(headerName));
181+
String value = getFirst(headerName);
182+
return (value != null ? Collections.singletonList(value) : null);
181183
}
182184

183185
Collection<String> values1 = servletResponse.getHeaders(headerName);

spring-web/src/test/java/org/springframework/http/server/ServletServerHttpResponseTests.java

+13
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,19 @@ void getHeaders() {
7575
assertThat(mockResponse.getCharacterEncoding()).as("Invalid Content-Type").isEqualTo("UTF-8");
7676
}
7777

78+
@Test
79+
void getHeadersWithNoContentType() {
80+
this.response = new ServletServerHttpResponse(this.mockResponse);
81+
assertThat(this.response.getHeaders().get(HttpHeaders.CONTENT_TYPE)).isNull();
82+
}
83+
84+
@Test
85+
void getHeadersWithContentType() {
86+
this.mockResponse.setContentType(MediaType.TEXT_PLAIN_VALUE);
87+
this.response = new ServletServerHttpResponse(this.mockResponse);
88+
assertThat(this.response.getHeaders().get(HttpHeaders.CONTENT_TYPE)).containsExactly(MediaType.TEXT_PLAIN_VALUE);
89+
}
90+
7891
@Test
7992
void preExistingHeadersFromHttpServletResponse() {
8093
String headerName = "Access-Control-Allow-Origin";

0 commit comments

Comments
 (0)