Skip to content

Commit 9c2ad4a

Browse files
committed
Improve forwarded URL support in HtmlUnit integration
Closes gh-28722
1 parent 1374d6d commit 9c2ad4a

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/ForwardRequestPostProcessor.java

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2022 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -19,28 +19,42 @@
1919
import org.springframework.mock.web.MockHttpServletRequest;
2020
import org.springframework.test.web.servlet.request.RequestPostProcessor;
2121
import org.springframework.util.Assert;
22+
import org.springframework.util.StringUtils;
2223

2324
/**
24-
* {@link RequestPostProcessor} for forward requests.
25+
* {@link RequestPostProcessor} to update the request for a forwarded dispatch.
2526
*
2627
* @author Rob Winch
2728
* @author Sam Brannen
29+
* @author Rossen Stoyanchev
2830
* @since 4.2
2931
*/
3032
final class ForwardRequestPostProcessor implements RequestPostProcessor {
3133

32-
private final String forwardUrl;
34+
private final String forwardedUrl;
3335

3436

35-
public ForwardRequestPostProcessor(String forwardUrl) {
36-
Assert.hasText(forwardUrl, "Forward URL must not be null or empty");
37-
this.forwardUrl = forwardUrl;
37+
public ForwardRequestPostProcessor(String forwardedUrl) {
38+
Assert.hasText(forwardedUrl, "Forwarded URL must not be null or empty");
39+
this.forwardedUrl = forwardedUrl;
3840
}
3941

4042
@Override
4143
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
42-
request.setServletPath(this.forwardUrl);
44+
request.setRequestURI(this.forwardedUrl);
45+
request.setServletPath(initServletPath(request.getContextPath()));
4346
return request;
4447
}
4548

49+
private String initServletPath(String contextPath) {
50+
if (StringUtils.hasText(contextPath)) {
51+
Assert.state(this.forwardedUrl.startsWith(contextPath), "Forward supported to same contextPath only");
52+
return (this.forwardedUrl.length() > contextPath.length() ?
53+
this.forwardedUrl.substring(contextPath.length()) : "");
54+
}
55+
else {
56+
return this.forwardedUrl;
57+
}
58+
}
59+
4660
}

0 commit comments

Comments
 (0)