Spring Boot @PathVariable Example

1. Introduction

The @PathVariable annotation in Spring Boot is used to extract values from the URI path. It is an essential tool for building RESTful web services where resource identification through URL patterns is required.

Key Points:

1. @PathVariable is used to bind a method parameter to a URI template variable.

2. It is commonly used in RESTful web services to access the unique identifiers of resources.

3. The annotated parameters within a controller method can be of simple types like int, long, String, etc., and Spring automatically converts the path segment to these types.

2. Implementation Steps

1. Start by creating a Spring Boot project with a web starter.

2. Define a controller class with request mapping methods.

3. Use @PathVariable to extract URI template variables within your controller methods.

4. Test the endpoints to ensure @PathVariable is correctly extracting the values from the URI.

3. Implementation Example

Here is the complete code that demonstrates the usage of @PathVariable annotation:
// Step 2: Define a controller with request mapping methods
@RestController
public class UserProfileController {

    // Step 3: Use @PathVariable to extract the 'id' URI template variable
    @GetMapping("/users/{id}")
    public ResponseEntity<String> getUserProfile(@PathVariable("id") Long userId) {
        // In practice, retrieve the user's profile using the provided 'userId'
        return ResponseEntity.ok("Profile for user: " + userId);
    }
}

// Step 4: Define the main application class
@SpringBootApplication
public class PathVariableExampleApplication {

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

Output:

Profile for user: 42

Explanation:

1. @RestController marks the UserProfileController as a controller suitable for handling HTTP requests in a RESTful manner.

2. @GetMapping("/users/{id}") defines a method that should handle GET requests for URLs following the pattern "/users/{id}".

3. @PathVariable("id") Long userId within the getUserProfile method indicates that userId should be bound to the {id} segment in the URI path.

4. PathVariableExampleApplication is the Spring Boot application class that contains the main method to bootstrap the application.

5. When an HTTP GET request is made to "/users/42", the getUserProfile method is called, and userId is assigned the value 42 from the URI.

6. The response "Profile for user: 42" is returned to the client, demonstrating that userId was successfully extracted from the URI path using @PathVariable.


Comments