0

Suppose a hyperlink is clicked and an url is fired with the following parameter list myparam1=myValue1&myparam2=myValue2&myparam3=myValue3 . Now how can I capture some of the parameters using @RequestParam in spring mvc?

My requirement is I have to capture some of the params and build the request to server. can I make all the request params as optional and used when required?

Suppose I want to use first two params and want to ignore the third. For eg. http://localhost:8080/api?myparam1=myValue1&myparam2=myValue2 and just not giving 3rd parameter in request.

In the next scenario, I want to use second and third and want to ignore the first parameter. For eg. http://localhost:8080/api?myparam2=myValue2&myparam3=myValue3 and just not giving 1st parameter in request.

In another scenario, I don't want to use any of the request param. For eg. http://localhost:8080/api and just not giving any parameters in request. is there any way I could achieve this? Please help...!

2 Answers2

0

You can capture all the params in a Map (the key is the name of the param) like this :

public void requestAllParams(@RequestParam Map<String, String> params)

You can also capture optional param using Optional like this :

public void requestParamOptional(@RequestParam(required=false) Optional<String> param)
Fabien
  • 974
  • 9
  • 14
0

A parameter with @RequestParam is by default required. It can be marked as not required:

@GetMapping
public ResponseEntity<Object> aMapping(@RequestParam String myparam1, @RequestParam String myparam2, @RequestParam(required = false) String myparam3) {
    // response
}
Thanus
  • 86
  • 4
  • Here we are making first two params as mandatory, I just want to make all the parameters as optional. I have improvised my query. – Naveen Kumar Jul 22 '20 at 06:58