1. Introduction
In Spring Boot, @RequestParam and @PathVariable are two annotations used for reading the values of request parameters. @RequestParam is used to extract query parameters from the query string of the HTTP request, while @PathVariable is used to extract values from the URI path.
2. Key Points
1. @RequestParam is used to access the query parameters from the URL (e.g., /api/items?name=Table).
2. @PathVariable is used to extract values from the URI path itself (e.g., /api/items/Table).
3. @RequestParam is typically optional and has a default value if not included in the request.
4. @PathVariable is usually required as part of the URI pattern.
3. Differences
@RequestParam | @PathVariable |
---|---|
Used to bind query parameter values (e.g., "/api?param=value"). | Used to bind URI template variables (e.g., "/api/{param}"). |
Optional with a default value possible. | Usually required as part of the URI. |
Can have multiple parameters in a single request. | Matches the pattern defined in the URI path. |
4. Example
@RestController
@RequestMapping("/api/items")
public class ItemController {
// Using @RequestParam to extract query parameter
@GetMapping
public String getItemByName(@RequestParam(name = "name") String name) {
return "Item requested: " + name;
}
// Using @PathVariable to extract from URI path
@GetMapping("/{name}")
public String getItemByPath(@PathVariable("name") String name) {
return "Item requested: " + name;
}
}
Output:
// No direct output, since this code is part of a Spring Boot controller.
Explanation:
1. When you call /api/items?name=Table, the getItemByName method will be invoked with "Table" as the parameter value through @RequestParam.
2. When you call /api/items/Table, the getItemByPath method will be invoked with "Table" as the parameter value through @PathVariable.
5. When to use?
- Use @RequestParam when the parameter is optional, or you need to handle complex scenarios with default values or not strictly tied to a URI structure.
- Use @PathVariable for required parameters that are a natural part of the URI and when you're modeling RESTful endpoints.
Comments
Post a Comment
Leave Comment