Close

Spring MVC - Binding @PathVariable to template URI specified at controller class level

In following example we are going to use URI template variable on a controller class level. We will then bind the template to @PathVariable used on the controller method.

Controller

@RestController
@RequestMapping("/users/{id}")
public class MyController {

  @GetMapping("/tasks")
  public String handleRequest(@PathVariable("id") String id) {
      return "tasks of user with id=" + id;
  }
}

Boot main class

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) throws InterruptedException {
      SpringApplication.run(ExampleMain.class, args);
  }
}

Running

To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

Or run the main method class from IDE.

Output

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.3.RELEASE
    Corresponding Spring Version 5.0.7.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 10
  • Maven 3.5.4

spring-mvc-path-variable-on-class Select All Download
  • spring-mvc-path-variable-on-class
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java

    See Also