Skip to content

Commit 3b5fa5a

Browse files
committed
Clean server.context-path if necessary
While the doc states that the default value is '/', setting that value explicitly will lead to an error since we enforce that the default root is the empty string. Changing the doc will probably be more confusing than anything else so we're now cleaning the user's provided value if necessary Closes spring-projectsgh-3554
1 parent 37edee4 commit 3b5fa5a

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,14 @@ public String getContextPath() {
139139
}
140140

141141
public void setContextPath(String contextPath) {
142-
this.contextPath = contextPath;
142+
this.contextPath = cleanContextPath(contextPath);
143+
}
144+
145+
private String cleanContextPath(String contextPath) {
146+
if (StringUtils.hasText(contextPath) && contextPath.endsWith("/")) {
147+
return contextPath.substring(0, contextPath.length() - 1);
148+
}
149+
return contextPath;
143150
}
144151

145152
public String getDisplayName() {

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import org.springframework.boot.context.embedded.ServletContextInitializer;
4242
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
4343

44+
import static org.hamcrest.Matchers.equalTo;
4445
import static org.hamcrest.core.IsInstanceOf.instanceOf;
4546
import static org.junit.Assert.assertEquals;
4647
import static org.junit.Assert.assertFalse;
@@ -123,6 +124,20 @@ public void testTomcatBinding() throws Exception {
123124
.getInternalProxies());
124125
}
125126

127+
@Test
128+
public void testTrailingSlashOfContextPathIsRemoved() {
129+
new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues(
130+
Collections.singletonMap("server.contextPath", "/foo/")));
131+
assertThat(this.properties.getContextPath(), equalTo("/foo"));
132+
}
133+
134+
@Test
135+
public void testSlashOfContextPathIsDefaultValue() {
136+
new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues(
137+
Collections.singletonMap("server.contextPath", "/")));
138+
assertThat(this.properties.getContextPath(), equalTo(""));
139+
}
140+
126141
@Test
127142
public void testCustomizeTomcat() throws Exception {
128143
ConfigurableEmbeddedServletContainer factory = mock(ConfigurableEmbeddedServletContainer.class);

0 commit comments

Comments
 (0)