Video in progress
What is the difference between @PathVariable and @RequestParam?
@PathVariable takes a piece of the URL path (/users/42), while @RequestParam takes a query parameter (/users?page=2). The first points to a resource, the second is for filters or options.
📖 Answer
@GetMapping("/orders/{id}")
public OrderDto one(@PathVariable long id) { ... } // /orders/15
@GetMapping("/orders")
public List<OrderDto> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(required = false) String status) { ... }
// /orders?page=1&status=PAID
A simple rule: one specific resource goes in the path (/orders/15); search, sorting and paging go in parameters (?status=PAID&sort=date).
The subtle parts:
@RequestParamis required by default; if the parameter is missing you get a 400. To make it optional, userequired = falseordefaultValue.- If the type doesn't match (
/orders/abcwhen alongis expected) — another 400. - If you compile with Java 8+ and the
-parametersflag, you don't need to write the name; Spring Boot sets this up for you.
Sign up to mark studied questions and save your progress.