diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index 86d9814c75..a27cd7d248 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -231,8 +231,14 @@ public class ServerProperties { } private String cleanContextPath(String contextPath) { - if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) { - return contextPath.substring(0, contextPath.length() - 1); + if (StringUtils.hasLength(contextPath)) { + // remove leading and trailing whitespaces if any exists + String ctxPath = StringUtils.trimWhitespace(contextPath); + + if (ctxPath.endsWith("/")) { + ctxPath = ctxPath.substring(0, ctxPath.length() - 1); + } + return ctxPath; } return contextPath; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index d09db2f56e..4b7f561c3b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -149,6 +149,32 @@ public class ServerPropertiesTests { assertThat(this.properties.getServlet().getContextPath()).isEqualTo(""); } + @Test + public void makeSureTrailingAndLeadingWhitespacesRemoved_case1() { + bind("server.servlet.context-path", " /assets"); + assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets"); + } + + @Test + public void makeSureTrailingAndLeadingWhitespacesRemoved_case2() { + bind("server.servlet.context-path", " /assets "); + assertThat(this.properties.getServlet().getContextPath()).isEqualTo("/assets"); + } + + @Test + public void makeSureTrailingAndLeadingWhitespacesRemoved_case3() { + bind("server.servlet.context-path", "/assets/copy/ "); + assertThat(this.properties.getServlet().getContextPath()) + .isEqualTo("/assets/copy"); + } + + @Test + public void makeSureTrailingAndLeadingWhitespacesRemoved_case4() { + bind("server.servlet.context-path", " /assets /copy/ "); + assertThat(this.properties.getServlet().getContextPath()) + .isEqualTo("/assets /copy"); + } + @Test public void testCustomizeUriEncoding() { bind("server.tomcat.uri-encoding", "US-ASCII");