Bean validation @Positive directive is not working on Integer @PathVariable

3.8k views Asked by At

I'm trying to validate a controller method (REST Api resource) Integer parameter with @Positive bean validation annotation, but nothing happens.

Java:
Java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

Spring Boot:
2.1.6.RELEASE

Code:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/{id}")
    public ResponseEntity<?> lista(@Valid @NotNull @Positive @PathVariable("id") Integer id) {
        String msg = "";
        if (id > 0) {
            msg = "id > 0";
        } else {
            msg = "id <= 0";
        }
        System.out.println(msg);
        return ResponseEntity.ok(msg);
    }
}


The @Positive is not doing what it is supposed to do.

Tests:

Request:
GET localhost:8080/test/0
Response:
200 OK "id <= 0"
Expected:
400 Bad Request

Request:
GET localhost:8080/test/-1
Response:
200 OK "id <= 0"
Expected:400 Bad Request


When I try GET localhost:8080/test/teste, I receive a 400 Bad Request, as expected.

1

There are 1 answers

1
pirho On BEST ANSWER

Had the same problem and solved it by applying

@Validated

on my controller. That should give you not HTTP 400 but HTTP 500.