Both @PathVariable and @RequestParam are used to receive data from the client request in Spring Boot.But they work in completely different ways.
What is @PathVariable?
- @PathVariable is used to get values directly from the URL path.
Example:
@GetMapping("/product/{id}")
public String getProduct(@PathVariable int id) {
return "Product ID: " + id;
}
URL:
/product/10
Here:
id = 10 => The value 10 becomes part of the URL path itself.
Usually used for:
- Specific resource IDs
- Mandatory values
Unique objects
What is @RequestParam?
@RequestParam gets values from query parameters.
Example:
@GetMapping("/products")
public String search(@RequestParam String category) {
return category;
}
URL:
/products?category=mobile
Here:
category = "mobile"
Usually used for:
- Filtering
- Searching
- Sorting
- Pagination
- Optional data
Examples:
/products?category=mobile
/products?page=2
/products?sort=price
/products?search=iphone
These are not unique resources.
They are conditions or filters.
Top comments (0)