1

I want to restrict the list of allowed request parameters in my controller, so that if I get a request with an undefined parameter in the controller, it should return a bad request, but it returns 200 OK.

I think that this one should be fixed on the framework level, but not in the controller layer. I am confused about it, and could not find anything on the internet

For e.g I have the following controller definition:

@GetMapping("/Client") public ResponseEntity<List<Client>> getAllClients(HttpServletRequest httpServletRequest, @RequestParam(value = McsConstants.PAGE_HEADER, required = false) Integer page, @RequestParam(value = McsConstants.SIZE_HEADER, required = false) Integer size) {...} 

And the valid request would be

GET .../Client GET .../Client?page=1 GET .../Client?size=10 GET .../Client?page=1&size=10 

How can I validate the case when I have an undefined request param like below?

GET .../Client?someUndefinedParam=1 

Let me know please for any ideas or links

Thanks!

2 Answers 2

2

One way to handle this can be using @RequestParam annotation on a Map or MultiValueMap argument.

The map is populated with all the request parameters, therein you can write your logic to validate and reject unidentified query params.

EDIT: Following is an example for the same-

@RequestMapping(value = "/test", method = RequestMethod.GET) public void testMethod(@RequestParam Map<String, String> allRequestParams) { if (!isValidParams(allRequestParams)) { // isValidParams() will validate the map with a reference map containing all the expected params // throw BadRequestException here } } 

Hope this helps!

Sign up to request clarification or add additional context in comments.

6 Comments

thanks! do you have an example on how to use a map with request param?
Sure, I'll add that in the answer..give me a few minutes.
Example added!!
If this helped you, would request you to accept the answer :)
Thanks, I will take a look a little bit later
|
0

let me share my knowledge it may helpful for some other scenarios

If the requestparam and variable is same name you no need to mention the value @RequestParam .

below i have mentioned with code example. Please share ur feedback

@GetMapping("/Client") public ResponseEntity<List<Client>> getAllClients(HttpServletRequest httpServletRequest, @RequestParam <Optional>Integer page, @RequestParam <Optional>Integer size) { //you can do ur logics } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.