我正在尝试以编程方式设置Spring Boot应用程序上下文根。上下文根的原因是我们希望应用程序可以从localhost:port/{app_name}访问,并有所有的控制器路径附加到它。

下面是web-app的应用程序配置文件。

@Configuration
public class ApplicationConfiguration {

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

  @Value("${mainstay.web.port:12378}")
  private String port;

  @Value("${mainstay.web.context:/mainstay}")
  private String context;

  private Set<ErrorPage> pageHandlers;

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

  @Bean
  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);
      factory.setPort(Integer.valueOf(port));
      factory.setContextPath(context);
      factory.setErrorPages(pageHandlers);
      return factory;
  }

  public String getPort() {
      return port;
  }

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

这里是主页面的索引控制器。

@Controller
public class IndexController {

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

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

}

应用程序的新根目录应该位于localhost:12378/主流,但它仍然位于localhost:12378。

是什么原因导致Spring Boot没有在请求映射之前追加上下文根?


当前回答

如果您使用Spring Boot 2。如果你想在命令行中传递context path属性,你应该像这样输入double //:

--server.servlet.context-path=//your-path

这招对我很管用。

其他回答

<!-- Server port-->

server.port=8080

<!--Context Path of the Application-->

server.servlet.context-path=/ems

如果您使用Spring Boot 2。如果你想在命令行中传递context path属性,你应该像这样输入double //:

--server.servlet.context-path=//your-path

这招对我很管用。

我们可以使用WebServerFactoryCustomizer设置它。这可以直接添加到spring引导main方法类中,该类会启动spring ApplicationContext。

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

如果你正在使用spring-boot-starter-webflux:

spring:
  webflux:
    base-path: /api

我对天发誓……我每次都忘记这一点。

对于以下Spring引导2版本,您需要使用以下代码

server:
   context-path: abc    

对于Spring引导2+版本使用下面的代码

server:
  servlet:
    context-path: abc