How to Add Context Path to Spring Boot Application
Spring Boot provides an easy way to set the context root for your application, allowing it to be accessed via localhost:port/{app_name}. Here's how to do it:
Use Application Properties:
Create a application.properties file in the src/main/resources directory and add the following properties:
server.contextPath=/mainstay
server.port=12378
Remove Custom Servlet Container Configuration:
If you have a custom servlet container configuration in your application, such as the EmbeddedServletContainerFactory, remove it.
Use EmbeddedServletContainerCustomizer:
If you need to perform post-processing on the servlet container, implement the EmbeddedServletContainerCustomizer interface and add it to your configuration. For example, to add error pages:
@Bean
public EmbeddedServletContainerCustomizer errorPageCustomizer() {
return factory -> {
ErrorPage notFoundPage = new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html");
ErrorPage forbiddenPage = new ErrorPage(HttpStatus.FORBIDDEN, "/forbidden.html");
factory.setErrorPages(Arrays.asList(notFoundPage, forbiddenPage));
};
}
Overriding Properties:
You can override the default properties set in application.properties by using an external properties file or JVM parameters.
This setup will set the context path to /mainstay and have your application run on port 12378. Your application will then be accessible via localhost:12378/mainstay.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3