Optimize content type parsing

This commit avoids calling HttpHeaders#getContentType multiple times in
ServletServerHttpResponse#writeHeaders.

Closes gh-32361
This commit is contained in:
Sébastien Deleuze 2024-03-04 13:24:50 +01:00
parent 4b96cd28c0
commit ce9dc19a3c
1 changed files with 7 additions and 5 deletions

View File

@ -27,6 +27,7 @@ import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode; import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@ -118,12 +119,13 @@ public class ServletServerHttpResponse implements ServerHttpResponse {
} }
}); });
// HttpServletResponse exposes some headers as properties: we should include those if not already present // HttpServletResponse exposes some headers as properties: we should include those if not already present
if (this.servletResponse.getContentType() == null && this.headers.getContentType() != null) { MediaType contentTypeHeader = this.headers.getContentType();
this.servletResponse.setContentType(this.headers.getContentType().toString()); if (this.servletResponse.getContentType() == null && contentTypeHeader != null) {
this.servletResponse.setContentType(contentTypeHeader.toString());
} }
if (this.servletResponse.getCharacterEncoding() == null && this.headers.getContentType() != null && if (this.servletResponse.getCharacterEncoding() == null && contentTypeHeader != null &&
this.headers.getContentType().getCharset() != null) { contentTypeHeader.getCharset() != null) {
this.servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name()); this.servletResponse.setCharacterEncoding(contentTypeHeader.getCharset().name());
} }
long contentLength = getHeaders().getContentLength(); long contentLength = getHeaders().getContentLength();
if (contentLength != -1) { if (contentLength != -1) {