Honor Host header for server name/port in MckHtSrvRq
Prior to this commit, the getServerName() and getServerPort() methods in MockHttpServletRequest simply returned the 'mocked' serverName and serverPort but ignored the 'Host' header entirely. Per the Servlet specification, however, these methods must parse the server name or port from the 'Host' header if it is present and otherwise fall back to the resolved server name or port. This commit fixes this by ensuring that getServerName() and getServerPort() properly parse the server's name or port from the 'Host' header if it is present in the request. If the 'Host' header is not present, MockHttpServletRequest falls back to returning the 'mocked' serverName and serverPort. Issue: SPR-12088
This commit is contained in:
@@ -107,6 +107,8 @@ public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
private static final String CONTENT_TYPE_HEADER = "Content-Type";
|
||||
|
||||
private static final String HOST_HEADER = "Host";
|
||||
|
||||
private static final String CHARSET_PREFIX = "charset=";
|
||||
|
||||
private static final ServletInputStream EMPTY_SERVLET_INPUT_STREAM =
|
||||
@@ -544,6 +546,19 @@ public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
@Override
|
||||
public String getServerName() {
|
||||
String host = getHeader(HOST_HEADER);
|
||||
if (host != null) {
|
||||
host = host.trim();
|
||||
if (host.startsWith("[")) {
|
||||
host = host.substring(1, host.indexOf(']'));
|
||||
}
|
||||
else if (host.contains(":")) {
|
||||
host = host.substring(0, host.indexOf(':'));
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
// else
|
||||
return this.serverName;
|
||||
}
|
||||
|
||||
@@ -553,6 +568,22 @@ public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
@Override
|
||||
public int getServerPort() {
|
||||
String host = getHeader(HOST_HEADER);
|
||||
if (host != null) {
|
||||
host = host.trim();
|
||||
int idx;
|
||||
if (host.startsWith("[")) {
|
||||
idx = host.indexOf(':', host.indexOf(']'));
|
||||
}
|
||||
else {
|
||||
idx = host.indexOf(':');
|
||||
}
|
||||
if (idx != -1) {
|
||||
return Integer.parseInt(host.substring(idx + 1));
|
||||
}
|
||||
}
|
||||
|
||||
// else
|
||||
return this.serverPort;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user