|
1 | 1 | /*
|
2 |
| - * Copyright 2002-2018 the original author or authors. |
| 2 | + * Copyright 2002-2022 the original author or authors. |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
|
19 | 19 | import org.springframework.mock.web.MockHttpServletRequest;
|
20 | 20 | import org.springframework.test.web.servlet.request.RequestPostProcessor;
|
21 | 21 | import org.springframework.util.Assert;
|
| 22 | +import org.springframework.util.StringUtils; |
22 | 23 |
|
23 | 24 | /**
|
24 |
| - * {@link RequestPostProcessor} for forward requests. |
| 25 | + * {@link RequestPostProcessor} to update the request for a forwarded dispatch. |
25 | 26 | *
|
26 | 27 | * @author Rob Winch
|
27 | 28 | * @author Sam Brannen
|
| 29 | + * @author Rossen Stoyanchev |
28 | 30 | * @since 4.2
|
29 | 31 | */
|
30 | 32 | final class ForwardRequestPostProcessor implements RequestPostProcessor {
|
31 | 33 |
|
32 |
| - private final String forwardUrl; |
| 34 | + private final String forwardedUrl; |
33 | 35 |
|
34 | 36 |
|
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; |
38 | 40 | }
|
39 | 41 |
|
40 | 42 | @Override
|
41 | 43 | public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
|
42 |
| - request.setServletPath(this.forwardUrl); |
| 44 | + request.setRequestURI(this.forwardedUrl); |
| 45 | + request.setServletPath(initServletPath(request.getContextPath())); |
43 | 46 | return request;
|
44 | 47 | }
|
45 | 48 |
|
| 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 | + |
46 | 60 | }
|
0 commit comments