Spring MVC and Web Layer
August 19, 2021

M05 Q08 What are the differences between @RequestParam and @PathVariable?

The main difference between @RequestParam and @PathVariable is a purpose of each annotation.

@PathVariable is responsible for mapping parts of URI, marked with usage of URI templates variables to controller method parameters. URI templates are identifiers surrounded with curly brackets.

@RequestParam is used to bind web request parameters to controller method parameter.

The other difference between @RequestParam and @PathVariable is following:

  • @RequestParam allows you to specify defaultValue property, @PathVariable does not

Similarities are following, both allows you to:

  • Specify name of variable to bind
  • Mark variables as required or optional
  • Use Java 8 Optional for optional values
  • Map all parameters to Map
  • Map list of values for parameter to collection