我正在尝试以编程方式设置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属性文件中

spring.data.rest.basePath=/your_path

其他回答

你可以像下面这样在Spring Boot: 2.1.6中使用:

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

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

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

正确的属性是

server.servlet.path

来配置DispatcherServlet的路径

and

server.servlet.context-path

来配置下面的应用程序上下文的路径。

您可以将此属性添加到spring属性文件中

spring.data.rest.basePath=/your_path

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

server:
   context-path: abc    

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

server:
  servlet:
    context-path: abc