Explain Codes LogoExplain Codes Logo

Add context path to Spring Boot application

java
spring-boot
server-configuration
context-path
Alex KataevbyAlex Kataev·Oct 21, 2024
TLDR

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:

# Look, Ma! I'm on the internet! server.servlet.context-path=/myapp

Or in application.yml:

# YAML, because JSON didn't have enough squiggly brackets server: servlet: context-path: /myapp

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:

# Because 8080 is so last year server.port=9090

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:

spring: application: name: myapp servlet: context-path: /myapp

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!