[IntelliJ IDEA] Config web server root context path in Spring Boot

Spring Boot, by default, serves content on the root context path (“/”). we’ll cover the different ways of configuring it.

Golbal Namespace

Config root context path of the application for appending golbal namespace as API prefix.

Use application.properties file

1
2
3
# src/main/resources/application.properties

server.servlet.contextPath=/api

Or use application.yaml file.

1
2
3
4
5
# src/main/resources/application.yaml

server:
servlet:
contextPath: /api

Then, vist http://localhost:8080/api/v1/users.

You can see Spring Boot Change Context Path | Baeldung - https://www.baeldung.com/spring-boot-context-path to learn the following options:

  • Java Config

  • Command Line Arguments

  • Java System Properties

  • OS Environment Variables

  • application.properties in Current Directory

  • application.properties in the classpath (src/main/resources or the packaged jar file)

Single Controller or Action

Config root context path prefix for single controller or action with annotations @RequestMapping or @GetMapping etc.

1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping(path = "api/users")
public class UsersController {

@GetMapping(path = "")
@ResponseBody
public String index(){
return userService.list();
}
}

Then, vist http://localhost:8080/api/users.

Custom properties

Config root context path prefix with your custom properties.

1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping(path = "${cloudolife.api}/users")
public class UsersController {

@GetMapping(path = "")
@ResponseBody
public String index(){
return userService.list();
}
}
1
2
3
# src/main/resources/application.properties

cloudolife.api=/api/v1

Or

1
2
3
4
# src/main/resources/application.yaml

cloudolife:
api: /api/v1

Then, vist http://localhost:8080/api/v1/users.

References

[1] 11. Server Properties | Common Application Properties - https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.server.server.servlet.context-path

[2] Spring Boot Change Context Path | Baeldung - https://www.baeldung.com/spring-boot-context-path

[3] How to add prefix /api to all of your URLs in Spring JAVA - https://www.coditty.com/code/how-to-add-prefix-api-to-all-of-your-urls-in-spring-java

[4] java - How to specify prefix for all controllers in Spring Boot? - Stack Overflow - https://stackoverflow.com/questions/28006501/how-to-specify-prefix-for-all-controllers-in-spring-boot