We use path variables and query parameters together to get specific and flexible information from a web request. Path variables identify a resource, and query parameters filter or add details.
Handling path variables and query params together in Spring Boot
@GetMapping("/resource/{id}")
public ResponseEntity<?> methodName(@PathVariable Type id, @RequestParam(required = false) Type param) {
// method body
}@PathVariable extracts values from the URL path.
@RequestParam extracts query parameters from the URL after the question mark.
@GetMapping("/users/{userId}") public String getUser(@PathVariable String userId, @RequestParam(required = false) String filter) { return "User: " + userId + ", Filter: " + filter; }
@GetMapping("/products/{category}") public String getProducts(@PathVariable String category, @RequestParam(defaultValue = "asc") String sort) { return "Category: " + category + ", Sort: " + sort; }
This Spring Boot controller has a method that takes an item ID from the URL path and an optional color from the query parameters. It returns a simple string showing both values.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ItemController { @GetMapping("/items/{itemId}") public String getItemDetails(@PathVariable String itemId, @RequestParam(required = false) String color) { if (color == null) { return "Item ID: " + itemId + ", Color: not specified"; } return "Item ID: " + itemId + ", Color: " + color; } }
If a query parameter is optional, set required = false to avoid errors when it's missing.
You can provide default values for query parameters using defaultValue in @RequestParam.
Path variables are part of the URL structure, while query parameters come after a question mark and can be many or none.
Use @PathVariable to get parts of the URL path.
Use @RequestParam to get query parameters after the URL path.
Combining both lets you build flexible and clear web endpoints.