我正在尝试以编程方式设置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没有在请求映射之前追加上下文根?


当前回答

我们可以在应用程序中设置它。属性是 API_CONTEXT_ROOT = / therootpath

我们在Java类中访问它,如下所述

@Value("${API_CONTEXT_ROOT}")
private String contextRoot;

其他回答

我们可以使用属性文件中的一个简单条目来更改上下文根路径。

application.properties

### Spring boot 1.x #########
server.contextPath=/ClientApp

### Spring boot 2.x #########
server.servlet.context-path=/ClientApp

请注意“服务器”。上下文路径”或“server.servlet。Context-path”[从springboot 2.0开始。X]属性只有在部署到嵌入式容器(例如,嵌入式tomcat)时才有效。例如,如果将应用程序作为war部署到外部tomcat,这些属性将不起作用。

请看这里的答案:https://stackoverflow.com/a/43856300/4449859

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

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

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

spring.data.rest.basePath=/your_path

它必须是: server.servlet。Context-path = / demo 注意它没有引号只有'/'前面的值 这个值会被放入应用程序中。属性文件