Spring @RequestParam annotation can be used to extract the query parameters in a handler method. In this quick tutorial, we’ll learn its usage.
Let’s first expose an API which returns a list of users with a given first name and age:
@RestController public class UserController { ... @GetMapping("/users") public List<User> getUsers(@RequestParam String firstName, @RequestParam int age) { return userService.findUsersWith(firstName, age); } }
curl -XGET 'http://localhost:8080/users?firstName=John&age=15' ... [{firstName = John ,lastName = Mason ,age = 15} , {firstName = John ,lastName = Dash ,age = 15}]
The @RequestParam annotation supports the usage of several attributes to cater to various common needs:
In the example we just covered, we’ll notice that the names of the method argument and query parameter were the same (firstName and age).
However, at times, we might feel the need to have different names. For that, we’ll use its name or value attribute:
@GetMapping("/users") public List<User> getUsers(@RequestParam(name="uName") String firstName , @RequestParam("uAge") int age) { return userService.findUsersWith(firstName, age); }
curl -XGET 'http://localhost:8080/users?uName=John&uAge=15'
By default, if we define a request parameter and don’t pass it in the user request, we’ll get an error.
To avoid that, we can set the required to false:
@GetMapping("/users") public List<User> getUsers(@RequestParam(required=false) String firstName , @RequestParam int age) { return userService.findUsersWith(firstName, age); }
http://localhost:8080/users?age=15
If we want to set the required to false and also map a default value to the concerned attribute, we’ll have:
@GetMapping("/users") public List<User> getUsers(@RequestParam(defaultValue="John") String firstName, @RequestParam int age) { return userService.findUsersWith(firstName, age); }
We can accept a list of query parameters in a Java List:
@GetMapping("/users/v2") public List<User> getUsersWithGivenAges(@RequestParam List<Integer> age) { return userService.findUsersWithAges(age); }
curl -XGET 'http://localhost:8080/users/v2?age=10,15,20' Or curl -XGET 'http://localhost:8080/users/v2?age=10&age=15&age=20'
To retrieve all passed query parameters from a user request, we’ll accept them as a Java Map:
@GetMapping("/paramsEx") public Map<String, String> printParams(@RequestParam Map<String, String> allQueryParams) { System.out.println(allQueryParams); return allQueryParams; }
curl -XGET 'http://localhost:8080/paramsEx?param1=A¶m2=B¶m3=2' ... {param1=A, param2=B, param3=2}
In this tutorial, we learned how to work with @RequestParam annotation in a Spring application.