How to Change Context Path in Spring Boot How to Change Context Path in Spring Boot

server.servlet.context-path

Page content

In this quick article, we learn how to change the servlet context path in the Spring Boot application.

Overview

Spring Boot web application, by default, serves the content at the root context path ("/") i.e. localhost:port/

Some application requires serving the content from a custom servlet context path e.g. localhost:port/myapp and require all the API request mappings should be appended to this context path e.g. localhost:port/myapp/users, localhost:port/myapp/dashboard, etc.

Spring Boot provides a property to change the context path which can be configured from application.properties, application.yml, or command-line argument.

Using Application Property

Set the property server.servlet.context-path to your custom context path for Spring Boot 2.x and above version like this:-

# Using application.properties
server.servlet.context-path=/myapp

# Using application.yml
server:
  servlet:
    context-path: /myapp

# Using command-line
$ java -jar -Dserver.servlet.context-path=/myapp spring-boot-app-1.0.jar

For Spring Boot 1.x, use this property instead:-

server.context-path=/myapp

When you start your application on a local machine. Your home page content is served at localhost:8080/myapp now.


For External Tomcat

Please note that this property only works with Spring Boot embedded containers e.g. Tomcat, Undertow, Jetty, etc. This property doesn’t work when you deploy the Spring boot web application to an external container like Tomcat using WAR.

To change the context path in external container, your WAR file name should match the context path e.g. myapp.war. You can change the WAR file name from the pom.xml like this:-

pom.xml
<build>
  ...
  <finalName>myapp</finalName>
</build>

Using Java Code

You have to provide a bean of WebServerFactoryCustomizer for Spring Boot 2.x and above version:-

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
    return factory -> factory.setContextPath("/myapp");
}

For Spring Boot 1.x, provide a bean of EmbeddedServletContainerCustomizer like this:-

@Bean
public EmbeddedServletContainerCustomizer<ConfigurableEmbeddedServletContainer> embeddedServletContainerCustomizer() {
    return container -> container.setContextPath("/myapp");
}

Using Environment Variable

You can also use OS environment variable to set the servlet context path for Spring Boot Application.

Use the following OS environment variable for Spring Boot 2.x and above version:-

UNIX
$ export SERVER_SERVLET_CONTEXT_PATH=/myapp

WINDOWS
> set SERVER_SERVLET_CONTEXT_PATH=/myapp

For Spring Boot 1.x, use:-

UNIX
$ export SERVER_CONTEXT_PATH=/myapp

WINDOWS
> set SERVER_CONTEXT_PATH=/myapp

That is all about this article. Thanks for Reading!