Skip to content

Commit bde2f85

Browse files
mrifnisnicoll
authored andcommitted
Trim trailing whitespace from spring.server.servlet.context-path
See gh-16165
1 parent 347daf6 commit bde2f85

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,14 @@ public void setContextPath(String contextPath) {
231231
}
232232

233233
private String cleanContextPath(String contextPath) {
234-
if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) {
235-
return contextPath.substring(0, contextPath.length() - 1);
234+
if (StringUtils.hasLength(contextPath)) {
235+
// remove leading and trailing whitespaces if any exists
236+
String ctxPath = StringUtils.trimWhitespace(contextPath);
237+
238+
if (ctxPath.endsWith("/")) {
239+
ctxPath = ctxPath.substring(0, ctxPath.length() - 1);
240+
}
241+
return ctxPath;
236242
}
237243
return contextPath;
238244
}

spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,32 @@ public void testSlashOfContextPathIsDefaultValue() {
149149
assertThat(this.properties.getServlet().getContextPath()).isEqualTo("");
150150
}
151151

152+
@Test
153+
public void makeSureTrailingAndLeadingWhitespacesRemoved_case1() {
154+
bind("server.servlet.context-path", " /assets");
155+
assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets");
156+
}
157+
158+
@Test
159+
public void makeSureTrailingAndLeadingWhitespacesRemoved_case2() {
160+
bind("server.servlet.context-path", " /assets ");
161+
assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets");
162+
}
163+
164+
@Test
165+
public void makeSureTrailingAndLeadingWhitespacesRemoved_case3() {
166+
bind("server.servlet.context-path", "/assets/copy/ ");
167+
assertThat(this.properties.getServlet().getContextPath())
168+
.isEqualTo("/assets/copy");
169+
}
170+
171+
@Test
172+
public void makeSureTrailingAndLeadingWhitespacesRemoved_case4() {
173+
bind("server.servlet.context-path", " /assets /copy/ ");
174+
assertThat(this.properties.getServlet().getContextPath())
175+
.isEqualTo("/assets /copy");
176+
}
177+
152178
@Test
153179
public void testCustomizeUriEncoding() {
154180
bind("server.tomcat.uri-encoding", "US-ASCII");

0 commit comments

Comments
 (0)