Search code examples
javaspringspring-restspring-validator

Spring REST - validating primitive GET request parameters


Is there a way to validate primitive (int, String etc.) GET parameters using annotations?

@RequestMapping(value = "/api/{someInt}",
    method = RequestMethod.GET,
    produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> someRestApiMethod(
    @PathVariable
    @Valid @Min(0) @Digits(integer=10, fraction=0)
    int someInt) {

    //...

    return new ResponseEntity<String>("sample:"+someInt, HttpStatus.OK);
}

As you see I have put a bunch of annotations to validate someInt to be a positive integer with 10 digits but still it accepts every kind of integers.


Solution

  • Yes, this is possible.

    Given the following controller:

    @RestController
    @Validated
    public class ValidatingController {
    
        @RequestMapping("/{id}")
        public int validatedPath(@PathVariable("id") @Max(9) int id) {
            return id;
        }
    
        @ExceptionHandler
        public String constraintViolationHandler(ConstraintViolationException ex) {
            return ex.getConstraintViolations().iterator().next()
                    .getMessage();
        }
    }
    

    and a MethodValidationPostProcessor registered in your context as follows (or XML equivalent, and not necessary with the Spring Boot web starter - it will do this for you):

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
    

    Assuming your dispatcher servlet is mapped to http://localhost:8080/:

    • accessing http://localhost:8080/9 gives 9
    • accessing http://localhost:8080/10 gives must be less than or equal to 9

    It looks like moves are afoot to make this easier/more automatic in future versions of Spring.