7

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.

DavidR
  • 5,542
  • 11
  • 52
  • 63
uylmz
  • 1,374
  • 1
  • 20
  • 35

2 Answers2

10

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.

ryanp
  • 4,446
  • 1
  • 29
  • 38
-1

As per JSR 303 this is not possible. See this for details

  • Simply sharing a link without describing what portion of the reference link mentions about the topic of the question, doesn't make sense. Moreover I have gone through the JSR303, and nowhere does it say that path variables cannot / should not be validated. – Divick Jan 29 '18 at 10:23