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


当前回答

如果你正在使用应用程序。Yml和spring 2.0以上版本,然后按以下方式配置。

server:
  port: 8081
  servlet:
     context-path: /demo-api

现在所有的API调用都像http://localhost:8081/demo-api/一样

其他回答

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

如果您使用Spring Boot 2.0.0,请使用:

server.servlet.context-path

在Spring Boot 1.5中:

在application.properties中添加以下属性:

server.context-path=/demo

注意:/demo是你的上下文路径URL。

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

application.properties

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

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

正确的属性是

server.servlet.path

来配置DispatcherServlet的路径

and

server.servlet.context-path

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