Using @PathVariable for URL Parameters in Spring Boot
📖 Scenario: You are building a simple Spring Boot web service that returns greetings for users based on their names provided in the URL.
🎯 Goal: Create a Spring Boot controller that uses @PathVariable to extract a user's name from the URL and return a greeting message.
📋 What You'll Learn
Create a Spring Boot controller class named GreetingController.
Add a method that handles GET requests to /greet/{name}.
Use @PathVariable to capture the name parameter from the URL.
Return a greeting message that includes the captured name.
💡 Why This Matters
🌍 Real World
Web services often need to get data from the URL path to customize responses, like user profiles or product details.
💼 Career
Understanding @PathVariable is essential for backend developers working with Spring Boot to build REST APIs.
Progress0 / 4 steps
1
Create the GreetingController class
Create a public class called GreetingController annotated with @RestController.
Spring Boot
Hint
Use @RestController to make the class a REST controller in Spring Boot.
2
Add a GET mapping method with @PathVariable
Inside GreetingController, add a public method called greetUser that handles GET requests to /greet/{name} using @GetMapping. The method should take a String name parameter annotated with @PathVariable.
Spring Boot
Hint
Use @GetMapping("/greet/{name}") and @PathVariable String name in the method signature.
3
Implement the greeting message
In the greetUser method, return a greeting string that says "Hello, " followed by the name parameter.
Spring Boot
Hint
Use string concatenation to combine "Hello, " and the name variable.
4
Add class-level request mapping
Add @RequestMapping("/api") annotation to the GreetingController class to prefix all routes with /api.
Spring Boot
Hint
Use @RequestMapping("/api") above the class to add a common URL prefix.
Practice
(1/5)
1. What is the main purpose of the @PathVariable annotation in Spring Boot?
easy
A. To bind form data to a Java object
B. To handle exceptions in controller methods
C. To define a fixed URL mapping for a controller method
D. To extract values from the URL path and pass them as method parameters
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 D
Quick Check:
@PathVariable = extract URL values [OK]
Hint: Remember: @PathVariable grabs values directly from URL path [OK]
Common Mistakes:
Confusing @PathVariable with @RequestParam
Thinking it binds form data
Assuming it handles exceptions
2. Which of the following is the correct syntax to use @PathVariable in a Spring Boot controller method to get an id from the URL /user/{id}?
easy
A. @GetMapping("/user/{id}") public String getUser(@PathVariable int id) { ... }
B. @GetMapping("/user") public String getUser(@PathVariable int id) { ... }
C. @GetMapping("/user/{id}") public String getUser(@RequestParam int id) { ... }
D. @GetMapping("/user/{id}") public String getUser(@PathVariable String name) { ... }
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 A
Quick Check:
URL {id} matches @PathVariable int id [OK]
Hint: URL placeholder and @PathVariable name must match [OK]
Common Mistakes:
Missing {id} in URL path
Using @RequestParam instead of @PathVariable
Mismatching parameter name and URL placeholder
3. Given the following Spring Boot controller method:
@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?
medium
A. electronics-42
B. 42-electronics
C. category-id
D. electronics42
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 A
Quick Check:
Return = category + "-" + id = electronics-42 [OK]
Hint: Match URL parts to parameters in order [OK]
Common Mistakes:
Swapping parameter order
Ignoring the dash '-' in return
Confusing @PathVariable with @RequestParam
4. Consider this Spring Boot controller method:
@GetMapping("/order/{orderId}")
public String getOrder(@PathVariable int id) {
return "Order: " + id;
}
What will happen when a client requests /order/100?
medium
A. Returns "Order: 0"
B. Returns "Order: 100"
C. Throws an error because parameter name does not match path variable
D. Returns null
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 C
Quick Check:
Parameter name must match path variable or specify name [OK]
Hint: Parameter name must match path variable or use @PathVariable("name") [OK]
Common Mistakes:
Assuming names can differ without annotation
Ignoring the need to specify variable name in @PathVariable
Expecting default value assignment
5. You want to create a Spring Boot controller method that handles URLs like /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?
hard
A. @GetMapping("/blog/{year}/{month}/{slug}")
public String getPost(@PathVariable int yr, @PathVariable int mo, @PathVariable String sl) { ... }
B. @GetMapping("/blog/{year}/{month}/{slug}")
public String getPost(@PathVariable("year") int y, @PathVariable("month") int m, @PathVariable("slug") String s) { ... }
C. @GetMapping("/blog/{year}/{month}/{slug}")
public String getPost(@PathVariable String year, @PathVariable String month, @PathVariable String slug) { ... }
D. @GetMapping("/blog/{year}/{month}/{slug}")
public String getPost(@PathVariable int y, @PathVariable int m, @PathVariable String s) { ... }
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 B
Quick Check:
Explicit name mapping allows different parameter names [OK]
Hint: Use @PathVariable("name") if parameter name differs from URL placeholder [OK]
Common Mistakes:
Using mismatched parameter names without specifying name
Using wrong data types for year/month
Assuming parameter names must always match URL placeholders
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.