Request Parameters
Data from the URL as method arguments
Some input data arrives not in the request body, but directly in the URL. Spring MVC can pass such values straight into Java method parameters, so the controller does not need to parse the request string manually.
Query parameters with @RequestParam
For the request GET /products?category=books&page=2,
the values after ? can be obtained conveniently with @RequestParam.
@GetMapping("/products")
List<ProductDto> products(
@RequestParam String category,
@RequestParam(defaultValue = "0") int page) {
return productService.find(category, page);
}
Spring MVC takes string values from the HTTP request and converts them into the declared Java types
when such conversion is supported. In the example, page becomes an
int, and when the parameter is missing the value 0 is used.
Path variables with @PathVariable
If a value is part of the path itself, it is marked with braces in the mapping
and obtained with @PathVariable.
@GetMapping("/products/{id}")
ProductDto product(@PathVariable long id) {
return productService.find(id);
}
The GET /products/42 request passes the value 42 into id.
The URL stays part of the external contract, while inside the controller we already work with a regular Java value.