Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-34

What is the difference between @RequestParam and @PathVariable?

Options

  1. They are identical; both read the value from the URL
  2. @PathVariable is from the path; @RequestParam the query (Correct option)
  3. @RequestParam is meant for reading JSON bodies only
  4. @PathVariable can only be used on POST requests

Answer

@PathVariable takes a value from the URL path (/users/42); @RequestParam takes it from the query string (/users?role=admin)

Why

Path variables identify a specific resource: /users/{id}.

Query parameters filter, sort or paginate a collection: /users?role=admin&page=2.

Both are bound to method parameters. @RequestParam can be optional with a default: @RequestParam(defaultValue = "0") int page.

Remember

Path = which resource. Query = how to filter/sort it.

Key terms

Practice this question in Repaso