Custom Context Path

While developing with Spring Boot and Rest Resources you may want to change your default context path.

By default this path is ” / “. So, when you start your application and want to navigate to your Rest Resource you just do

http://localhost:<yourPort>

and everything is fine. I´ll show you how to change this. For example if you want to navigate to “/myWebApp”.

Application Properties

server.servlet.contextPath=/myWebApp

Application Yml

server:
  servlet:
    contextPath: /myWebApp

Programmatic configuration

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

/**
 *
 * @author javadevcorner.com
 */
@Component
public class ProgrammaticContextPath implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.setContextPath("/myWebApp");
    }
}

You don´t need to make any further this in this approach. The configuration will be autodetected by Spring Boot on start up.

Result

After you´ve done any of this approaches your application can be called by

http://localhost:<yourPort>/myWebApp

 

Feel free to share