Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-26 20:23:03
Original
814 people have browsed it

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>
    Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!