About @RequestParam
It binds the value of the query string parameter name into the name parameter of the method. If the name parameter is absent in the request, the defaultValue of the is used. by default required is true for the parameter.
Example1: request parameter name must be same is argument parameter name. (i.e. id)
public String getData( String id) { return "ID is: " + id; }
Example2- name: If request parameter is different than the argument parameter name then we can specify the name of parameter in the name attribute. i.e. name="id"
we can also write like this : @RequestParam("id").
@GetMapping("/set/data") public String setData( String uid) { return "UID: " + uid; }
Example3- required: By default required is true. So, if parameter will not be present in the request it will give below error.
400 Bad Request
Required String parameter 'id' is not present
public String getData((required = false) String id) {
return "ID is: " + id; }
Example4- Default value: If parameter is not there in the request then it will take the provided default value.
we can specify the default value using : defaultValue = "testId"
public String getData((defaultValue = "testId") String id) {
return "ID is: " + id; }
Example5: Mapping all parameters:
We can map app the parameter without specifying their name. here it will store all parameters in the paramsMap parameter,
public String setData( Map<String,String> paramsMap) { return "All Params: " + paramsMap.entrySet(); }
Example6: Store all parameters in list.
Here it will store all parameters in the ids list
public String getData( List<String> ids) {
return "IDs : " + ids; }