@PathVariable lets you get parts of the URL as variables in your code. This helps your app respond differently based on the URL.
@PathVariable for URL parameters in Spring Boot
@GetMapping("/path/{variableName}")
public ReturnType methodName(@PathVariable Type variableName) {
// use variableName here
}The part in curly braces {} in the URL is the variable name.
The method parameter annotated with @PathVariable must match the variable name in the URL.
@GetMapping("/user/{id}") public String getUser(@PathVariable String id) { return "User ID: " + id; }
@GetMapping("/order/{orderId}/item/{itemId}") public String getOrderItem(@PathVariable int orderId, @PathVariable int itemId) { return "Order: " + orderId + ", Item: " + itemId; }
@GetMapping("/product/{name}") public String getProduct(@PathVariable(name = "name") String productName) { return "Product: " + productName; }
This simple Spring Boot controller has one URL endpoint /user/{id}. When you visit /user/45, it returns 'User ID received: 45'.
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("/user/{id}") public String getUserById(@PathVariable String id) { return "User ID received: " + id; } }
If the method parameter name matches the path variable name, you can omit the name attribute in @PathVariable.
Path variables are always strings but Spring can convert them to other types like int or long automatically.
Use @PathVariable only for parts of the URL path, not for query parameters (use @RequestParam for those).
@PathVariable extracts values from the URL path.
It helps create dynamic and readable URLs.
Use it in Spring Boot controller methods with @GetMapping or other mapping annotations.
Practice
@PathVariable annotation in Spring Boot?Solution
Step 1: Understand the role of @PathVariable
@PathVariable is used to get dynamic parts of the URL and pass them to method parameters.Step 2: Compare with other annotations
Other options like binding form data or exception handling are done by different annotations, not @PathVariable.Final Answer:
To extract values from the URL path and pass them as method parameters -> Option DQuick Check:
@PathVariable = extract URL values [OK]
- Confusing @PathVariable with @RequestParam
- Thinking it binds form data
- Assuming it handles exceptions
@PathVariable in a Spring Boot controller method to get an id from the URL /user/{id}?Solution
Step 1: Match URL pattern with method parameter
The URL has {id}, so the method must have @PathVariable int id to match the placeholder.Step 2: Check annotation and parameter type
@GetMapping("/user/{id}") public String getUser(@PathVariable int id) { ... } correctly uses @PathVariable with int id and matches the URL pattern.Final Answer:
@GetMapping("/user/{id}") public String getUser(@PathVariable int id) { ... } -> Option AQuick Check:
URL {id} matches @PathVariable int id [OK]
- Missing {id} in URL path
- Using @RequestParam instead of @PathVariable
- Mismatching parameter name and URL placeholder
@GetMapping("/product/{category}/{id}")
public String getProduct(@PathVariable String category, @PathVariable int id) {
return category + "-" + id;
}What will be the output when a client requests
/product/electronics/42?Solution
Step 1: Identify parameter values from URL
URL /product/electronics/42 means category = "electronics", id = 42.Step 2: Understand return statement
The method returns category + "-" + id, so it returns "electronics-42".Final Answer:
electronics-42 -> Option AQuick Check:
Return = category + "-" + id = electronics-42 [OK]
- Swapping parameter order
- Ignoring the dash '-' in return
- Confusing @PathVariable with @RequestParam
@GetMapping("/order/{orderId}")
public String getOrder(@PathVariable int id) {
return "Order: " + id;
}What will happen when a client requests
/order/100?Solution
Step 1: Check URL placeholder and method parameter names
URL has {orderId}, but method parameter is named id without specifying name in @PathVariable.Step 2: Understand default matching behavior
Without specifying the name in @PathVariable, Spring tries to match parameter name to path variable name. They differ, causing an error.Final Answer:
Throws an error because parameter name does not match path variable -> Option CQuick Check:
Parameter name must match path variable or specify name [OK]
- Assuming names can differ without annotation
- Ignoring the need to specify variable name in @PathVariable
- Expecting default value assignment
/blog/{year}/{month}/{slug} where year and month are integers and slug is a string. Which of the following method signatures correctly uses @PathVariable to extract these values?Solution
Step 1: Match URL placeholders with method parameters
The URL has {year}, {month}, {slug}. Method parameters must match these names or specify them explicitly.Step 2: Check parameter names and @PathVariable usage
@GetMapping("/blog/{year}/{month}/{slug}") public String getPost(@PathVariable("year") int y, @PathVariable("month") int m, @PathVariable("slug") String s) { ... } uses different parameter names (y, m, s) but explicitly maps them to URL placeholders using @PathVariable("name"), which is correct.Final Answer:
@GetMapping("/blog/{year}/{month}/{slug}") public String getPost(@PathVariable("year") int y, @PathVariable("month") int m, @PathVariable("slug") String s) { ... } -> Option BQuick Check:
Explicit name mapping allows different parameter names [OK]
- Using mismatched parameter names without specifying name
- Using wrong data types for year/month
- Assuming parameter names must always match URL placeholders
Ready to prove it?
Pass the test and this pattern moves unknown
