Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
uylmz Avatar asked Dec 08 '15 15:12

uylmz


1 Answers

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.

like image 67
ryanp Avatar answered Oct 16 '22 11:10

ryanp