Spring Boot Context Root

By : CorreyS
Source: Stackoverflow.com

I am trying to set a Spring Boot applications context root programatically. The reason for the context root is we want the app to be accessed from localhost:port/{app_name} and have all the controller paths append to it.

Here is the application configuration file for the web-app.

public class ApplicationConfiguration {

  Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);

  private String port;

  private String context;

  private Set<ErrorPage> pageHandlers;

  private void init(){
      pageHandlers = new HashSet<ErrorPage>();
      pageHandlers.add(new ErrorPage(HttpStatus.NOT_FOUND,"/notfound.html"));
      pageHandlers.add(new ErrorPage(HttpStatus.FORBIDDEN,"/forbidden.html"));

  public EmbeddedServletContainerFactory servletContainer(){
      TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
      logger.info("Setting custom configuration for Mainstay:");
      logger.info("Setting port to {}",port);
      logger.info("Setting context to {}",context);
      return factory;

  public String getPort() {
      return port;

  public void setPort(String port) {
      this.port = port;

Here is the index controller for the main page.

public class IndexController {

  Logger logger = LoggerFactory.getLogger(IndexController.class);

  public String index(Model model){
      logger.info("Setting index page title to Mainstay - Web");
      model.addAttribute("title","Mainstay - Web");
      return "index";


The new root of the application should be at localhost:12378/mainstay but it is still located at localhost:12378.

What am I missing that is causing Spring Boot to not append the context root before the request mapping?

By : CorreyS


We can set it in the application.properties as API_CONTEXT_ROOT=/therootpath

And we access it in the java class as mentioned below @Value("${API_CONTEXT_ROOT}") private String contextRoot;

By : Sanket

This video can help you solving your question :)
By: admin