Discover how to stop wrestling with URLs and let Spring Boot handle the messy details for you!
Why Handling path variables and query params together in Spring Boot? - Purpose & Use Cases
Imagine building a web service where you manually parse URLs to get both path parts and query details, like extracting user IDs from the path and filters from the query string.
Manually splitting and parsing URLs is error-prone, hard to maintain, and can easily break when URL formats change or when multiple parameters are involved.
Spring Boot lets you declare path variables and query parameters right in your method signatures, so the framework handles parsing and validation automatically.
String url = "/users/123?active=true"; // manually split and parse path and query
@GetMapping("/users/{id}")
public ResponseEntity<?> getUser(@PathVariable String id, @RequestParam boolean active) { ... }This makes your code cleaner, safer, and easier to read while letting you focus on business logic instead of URL parsing.
When building an API to fetch user details by ID and filter results by status or date, you can easily get both from the URL without extra parsing code.
Manual URL parsing is complex and fragile.
Spring Boot automates extracting path and query parameters.
This leads to cleaner, more reliable web service code.
Practice
Solution
Step 1: Understand URL parts
The URL path segment is the part of the URL that defines the resource location, like /users/{id}.Step 2: Identify the correct annotation
@PathVariable is used to bind a method parameter to a URI template variable in the path.Final Answer:
@PathVariable -> Option AQuick Check:
Path segment value = @PathVariable [OK]
- Confusing @RequestParam with @PathVariable
- Using @RequestBody for path variables
- Trying to get path variables from headers
id and a query parameter sort in Spring Boot?Solution
Step 1: Match annotations to parameter types
Path variables come from the URL path, so use @PathVariable forid. Query parameters come after ?, so use @RequestParam forsort.Step 2: Check method signature correctness
public String getUser(@PathVariable String id, @RequestParam String sort) correctly uses @PathVariable foridand @RequestParam forsort.Final Answer:
public String getUser(@PathVariable String id, @RequestParam String sort) -> Option AQuick Check:
Path variable = @PathVariable, Query param = @RequestParam [OK]
- Swapping @PathVariable and @RequestParam
- Using @PathVariable for query parameters
- Missing one of the annotations
@GetMapping("/items/{itemId}")
public String getItem(@PathVariable String itemId, @RequestParam(defaultValue = "asc") String order) {
return itemId + "-" + order;
}What will be the output when a client requests
/items/42?order=desc?Solution
Step 1: Identify values from URL
Path variableitemIdis "42" from /items/42. Query parameterorderis "desc" from ?order=desc.Step 2: Understand method return
The method returnsitemId + "-" + order, so "42-desc".Final Answer:
"42-desc" -> Option BQuick Check:
Path variable + query param = "42-desc" [OK]
- Ignoring query parameter and using default
- Mixing order of concatenation
- Expecting error when query param is present
@GetMapping("/books/{bookId}")
public String getBook(@PathVariable int bookId, @RequestParam int page) {
return "Book: " + bookId + ", Page: " + page;
}What error will occur if a client calls
/books/abc?page=2?Solution
Step 1: Check path variable type
The method expectsbookIdas int, but URL provides "abc" which is not a number.Step 2: Understand Spring Boot behavior on type mismatch
Spring Boot returns 400 Bad Request when it cannot convert path variable to required type.Final Answer:
400 Bad Request due to type mismatch -> Option CQuick Check:
Type mismatch in @PathVariable causes 400 error [OK]
- Expecting 404 Not Found instead of 400
- Assuming null page causes error
- Thinking method returns string with invalid input
filter. If filter is missing, it should default to "all". Which method signature correctly implements this behavior?Solution
Step 1: Identify path variable usage
User ID is part of the URL path, so use @PathVariable foruserId.Step 2: Handle optional query parameter with default
Use @RequestParam withdefaultValue = "all"to provide a default whenfilteris missing.Final Answer:
public String getUser(@PathVariable String userId, @RequestParam(defaultValue = "all") String filter) -> Option DQuick Check:
Default query param value = @RequestParam(defaultValue) [OK]
- Using @RequestParam(required = true) for optional params
- Using @RequestParam without defaultValue causing errors
- Confusing @RequestParam and @PathVariable roles
Ready to prove it?
Pass the test and this pattern moves unknown
