Add context path to Spring Boot application
To set the context path for your Spring Boot application, use server.servlet.context-path in your application.properties or application.yml file.
For application.properties:
Or in application.yml:
Now everyone online can find your app at http://localhost:8080/myapp.
Advanced Tips & Tricks
Changing Server Port: Adding a server.port property lets you specify a dedicated port where your app will be accessible:
Embedding in Containers: server.servlet.context-path won't work its magic if you're deploying your app to an external server like Tomcat. Instead, define the context path directly in the server's config files.
Fiddling with DispatcherServlet Path: Tweaking server.servlet.path changes the path for the DispatcherServlet. It's no context path, but it lets you show off your DispatcherServlet in style.
Customization with the Big Guns: For stuff like SSL and setting up multiple connectors, you might want to pull out the EmbeddedServletContainerCustomizer. It's kinda like setting the EQ on your stereo, but for your web server instead.
Testing, 1, 2, 3: Always test your application. Otherwise, how else are you going to catch that one typo that brought the entire app down?
Edge Cases & Possible Gotchas
External Tomcat Deployment: This just in—server.context-path doesn't work when pushing your app to an external Tomcat. Instead, use META-INF/context.xml in the WAR.
YAML Property Expansion: You've got more than enough indentation! Expand those YAML properties for the sake of clarity:
Overriding Run-Time Properties: java -jar myapp.jar too boring for you? Try adding --server.port=9090 --server.servlet.context-path=/myapi for some excitement!
It's Spring Boot, Not Spring Bootleg: Using the wrong property names? Maybe your Spring Boot version is to blame. Check and make sure you're using the right properties.
Actuator Endpoints: Got Spring Boot Actuator? server.servlet.context-path applies to management endpoints too, so remember to update them!
Was this article helpful?