@RequestParam is used to bind the request parameters to Controllers method parameter. @RequestParam has 2 attributes that can be used required and defaultValue. We will see examples of both these attributes.
Using @RequestParam in Spring MVC
1 2 3 4 5 6 |
@RequestMapping("/employee") public String employeeDetails(@RequestParam("id") String id, @RequestParam("name") String name) { // Implement your logic here } |
In the above code if a URL /employee?id=123&name=Steve then the Method param id will get the value 123 and name will get Steve.
How to make @RequestParam optional
Parameters using @RequestParam are required by default. You can make those params optional using the attribute required set to false.
1 2 3 4 5 6 7 |
@RequestMapping("/employee") public String employeeDetails(@RequestParam(value = "id", required = false) String id, @RequestParam("name") String name) { // Implement your logic here } |
How to give @RequestParam a default value
You can give default values to the Request params using the defaultValue attribute.
1 2 3 4 5 6 |
@RequestMapping("/employee") public String employeeDetails(@RequestParam(value = "id", defaultValue = "100") String id) { // Implement your logic here } |
So in the above code if you do not specify any id param, then the method param will get a default value of 100.
Please Note: If you use
/employee?id= that will mean you are passing a param with no value. And that will end up in passing a null value to the id param in the method.
Default Value will only be applied when no param of that name is passed at all.
Hope you were able to get some info on Using @RequestParam in Spring MVC.