Home  >  Article  >  Java  >  How to Programmatically Set the Context Path for a Spring Boot Application?

How to Programmatically Set the Context Path for a Spring Boot Application?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 20:23:03805browse

How to Programmatically Set the Context Path for a Spring Boot Application?

Add Context Path to Spring Boot Application

Question:

I am unable to set a Spring Boot application's context root programmatically. The goal is to access the application at localhost:port/{app_name} and have controller paths appended to it. However, the application remains accessible at localhost:port.

Answer:

Instead of rolling your own solution, utilize Spring Boot's built-in support for setting the context path.

Solution:

  1. Create an application.properties file in src/main/resources.
  2. Add the following properties:

    <code class="properties">server.contextPath=/mainstay
    server.port=12378</code>

Update for Spring Boot 2.0:

In Spring Boot 2.0, the context path is now configured as:

<code class="properties">server.servlet.context-path=/mainstay</code>

Note:

  • The properties in application.properties serve as defaults.
  • You can override these properties at runtime using a separate application.properties file or JVM parameters.
  • Remove the custom servlet container configuration.
  • Instead, consider using an EmbeddedServletContainerCustomizer implementation to handle any necessary container post-processing.

Reference:

  • [Spring Boot Server Properties](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties)

The above is the detailed content of How to Programmatically Set the Context Path for a Spring Boot Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn