If I have a method that has like 10 request parameters and I may not always need all of them
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@RequestParam String optionalRequestParam1,
@RequestParam String optionalRequestParam2,
...
@RequestParam String optionalRequestParam10)
So in this header I'd like something that is like
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@RequestParam RequestParamBuilder requestParamBuilder)
and then it would just build an object for me with all valid parameters sent through filled out and the rest being null or something
CodePudding user response:
You can have multiple parameters without defining their names by just using a Map
:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@RequestParam Map<String, Object> params) {
log.info("Params: {}", params.entrySet();
}
How to make the call:
curl --location --request GET 'http://localhost:8080/whatever?integer=45&string="some text"&boolean=true'
Output:
Params: [integer=45, string="some text", boolean=true]
CodePudding user response:
If you wanted the parameters to be passed into an object, you can use a POJO as you were but remove the @RequestParam notation:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(RequestParamBuilder requestParamBuilder)
Then create a class for RequestParamBuilder
. You can mark the fields inside the POJO as @NotNull
etc to handle validation and build out the object with only the params that were included in the request, but the POJO must be annotated with @Valid
if you wish for spring to validate it this way:
@GetMapping("/whatever")
public ResponseEntity<String> sendSomethingBack(@Valid RequestParamBuilder requestParamBuilder)