spring boot validation of request parameters - @NotNull is not working

268 views Asked by At

I am trying to add Validation for my request parameters of my rest endpoint. I see that @NotBlank is working as expected and throwing Constraint violation exception while @NotNull is not.

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
    @RestController
    @RequestMapping("/test")
    @Validated
    class MyController{
    
    
        @GetMapping(value = "/data", produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Data> getData(
             @RequestParam @NotNull(message = "age is required") Integer age,
             @RequestParam @NotBlank(message = "name is required") String name){
              
             //do something  
         }
    }

Dependency Used : implementation 'org.springframework.boot:spring-boot-starter-validation'

when I try to hit following endpoints from my postman to test this,

http://localhost:8080/myApp/test/data?age=&name='myname' - doesn't throw constraintviolationexception

http://localhost:8080/myApp/test/data?age=null&name='myname' - doesn't throw constraintviolationexception

http://localhost:8080/myApp/test/data?name='myname' - doesn't throw constraintviolationexception

http://localhost:8080/myApp/test/data?age=22&name='' - throws constraintviolationexception

java version used : Java 17 spring boot version : 2.7.7

Any Idea what I might be missing ?

0

There are 0 answers