How to Get Path Variable in Spring Boot: Simple Guide
In Spring Boot, you get a path variable by using the
@PathVariable annotation in your controller method parameters. This annotation binds a variable from the URL path directly to a method argument, allowing you to access dynamic values from the URL.Syntax
The @PathVariable annotation is used in a Spring Boot controller method to bind a URI template variable to a method parameter.
@PathVariable: Marks the method parameter as a path variable.valueorname: Optional attribute to specify the variable name if it differs from the parameter name.- Method parameter: The variable that receives the path value.
java
public String getUser(@PathVariable String id) { // use id variable }
Example
This example shows a Spring Boot REST controller with a GET endpoint that extracts a user ID from the URL path using @PathVariable. When you visit /users/42, the method receives 42 as the id parameter.
java
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/users/{id}") public String getUserById(@PathVariable String id) { return "User ID is: " + id; } }
Output
User ID is: 42
Common Pitfalls
Common mistakes when using @PathVariable include:
- Not matching the path variable name in the URL and the method parameter name.
- Forgetting to use
@PathVariableannotation on the method parameter. - Using a different variable name in the annotation without specifying it explicitly.
Example of a mistake and the fix:
java
// Wrong: variable name mismatch without specifying name @GetMapping("/items/{itemId}") public String getItem(@PathVariable String id) { return id; // This will cause an error } // Correct: specify variable name in annotation @GetMapping("/items/{itemId}") public String getItem(@PathVariable("itemId") String id) { return id; // Works correctly }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| @PathVariable | Binds URL path variable to method parameter | @PathVariable String id |
| Variable name match | Parameter name must match path variable or specify name | @PathVariable("userId") String id |
| Optional name | Use when parameter name differs from path variable | @PathVariable(name = "id") String userId |
| Multiple variables | Use multiple @PathVariable for multiple path parts | @GetMapping("/users/{userId}/posts/{postId}") |
Key Takeaways
Use @PathVariable to bind URL path variables to controller method parameters.
Ensure the variable name in the URL matches the method parameter or specify it explicitly.
Always annotate the method parameter with @PathVariable to avoid errors.
You can extract multiple path variables by adding multiple @PathVariable parameters.
This technique helps create dynamic REST endpoints in Spring Boot.