0

How can I make a Spring @Controller return a 400 status code if the client sends any unexpected request parameters?

For example, I have this

    public ResponseEntity<String> recommend(
        @RequestParam(value = "max-age-seconds", required = false) Long maxAgeSeconds) {
        ...
    }

And the client may have a typo in max-age-seconds, which my application won't recognise and then fallback to the default max age I chose at a later time.

I know I could get the list of all the request parameters with request.getParameterNames() and check one by one, but I'm looking for a neater and more efficient solution.

EDIT: I just found out that 4 years ago it didn't have a built-in solution, I wonder if it's still the case.

Community
  • 1
  • 1
cahen
  • 15,807
  • 13
  • 47
  • 78
  • I don't think there is a better solution... you need to loop through request params and chek if there are unexpected parameters. – davioooh Feb 15 '17 at 17:14

1 Answers1

0

How about you call the method request.getParameterMap() and then check that the size of your Map is 1 the key equals "max-age-seconds" and you can even validate the value if you wish. if any of your validations goes wrong then return 400 (or may be 300 with error message "This is Sparta!"). (the last part is a joke...)

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36