Path RequestPredicate should honor servlet path

Closes gh-23841
This commit is contained in:
Arjen Poutsma 2019-10-31 16:00:02 +01:00
parent 95af079906
commit 3858a69c42
3 changed files with 27 additions and 0 deletions

View File

@ -54,8 +54,10 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriBuilder;
import org.springframework.web.util.UrlPathHelper;
/**
* {@code ServerRequest} implementation based on a {@link HttpServletRequest}.
@ -111,6 +113,16 @@ class DefaultServerRequest implements ServerRequest {
return ServletUriComponentsBuilder.fromRequest(servletRequest());
}
@Override
public String path() {
String path = (String) servletRequest().getAttribute(HandlerMapping.LOOKUP_PATH);
if (path == null) {
UrlPathHelper helper = new UrlPathHelper();
path = helper.getLookupPathForRequest(servletRequest());
}
return path;
}
@Override
public Headers headers() {
return this.headers;

View File

@ -168,6 +168,8 @@ public class RouterFunctionMapping extends AbstractHandlerMapping implements Ini
@Nullable
@Override
protected Object getHandlerInternal(@NotNull HttpServletRequest servletRequest) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(servletRequest);
servletRequest.setAttribute(LOOKUP_PATH, lookupPath);
if (this.routerFunction != null) {
ServerRequest request = ServerRequest.create(servletRequest, this.messageConverters);
servletRequest.setAttribute(RouterFunctions.REQUEST_ATTRIBUTE, request);

View File

@ -116,6 +116,19 @@ public class RequestPredicatesTests {
assertThat(predicate.test(request)).isFalse();
}
@Test
public void servletPath() {
MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/foo/bar");
servletRequest.setServletPath("/foo");
ServerRequest request = new DefaultServerRequest(servletRequest, emptyList());
RequestPredicate predicate = RequestPredicates.path("/bar");
assertThat(predicate.test(request)).isTrue();
servletRequest = new MockHttpServletRequest("GET", "/foo");
request = new DefaultServerRequest(servletRequest, emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
public void pathNoLeadingSlash() {
MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path");