1

I have a REST endpoint accepting some request parameters (let's call them one and two), all optional. I would like to send a 400 Bad Request response if one of them is misspelled (say tow instead of two). That would be the same thing as checking for unexpected parameters (like three).

So I would send 200 on:

  • GET /
  • GET /?one=1
  • GET /?two=2
  • GET /?one=1&two=2

And I would send 400 on:

  • GET /?tow=2
  • GET /?three=3

How could I do this easily with Spring? I know how to specify expected parameters, but what about the unexpected ones?

My first idea was to have some sort of dictionary of allowed values and check it explicitly, but I would have to do this on every request method. There's got to be a better way.

@RestController
public class StrictController {

    private static final String[] ALLOWED_PARAMS = { "one", "two" };

    @GetMapping
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseEntity<Object> strict(
            @RequestParam(name = "one", required = false) String one,
            @RequestParam(name = "two", required = false) String two,
            HttpServletRequest request) {
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            if (!paramAllowed(paramNames.nextElement())) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
        }
        return ResponseEntity.ok(null);
    }

    private boolean paramAllowed(String paramName) {
        for (String allowedName : ALLOWED_PARAMS) {
            if (allowedName.toLowerCase().equals(paramName.toLowerCase())) {
                return true;
            }
        }
        return false;
    }
}

If you want to try this out, I have a MVCE.

Cos64
  • 1,617
  • 2
  • 19
  • 30
  • 1
    Does [this](https://stackoverflow.com/questions/10010176/spring-mvc-how-to-check-that-no-unexpected-query-string-parameters-has-been-pa) answer your question? – wjans May 29 '20 at 12:08
  • Yes it does, thank you for the link! I added [a branch](https://gitlab.com/dev-samples/strict-request-param/-/tree/handler_interceptor) on my MVCE with the solution inspired by [the accepted answer](https://stackoverflow.com/a/10018783/479288) on that other question. – Cos64 May 29 '20 at 17:27

0 Answers0