0

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 ?

8
  • Did you use the proper @NotNull? Commented Sep 28, 2023 at 5:43
  • yes I am using javax.validation.constraints.NotNull; Commented Sep 28, 2023 at 14:57
  • Try to use also @Valid annotation Commented Sep 28, 2023 at 16:27
  • @Wikimmax Yeah even tried that adding before requestparam but it didn't work. Commented Sep 28, 2023 at 23:49
  • I would suggest to simply create a wrapper class which would bind the parameters instead of using query parameters. That way you can annotate the fields in that class and just use @Valid on the method argument (and don' tneed the @Validated on the class. Commented Sep 29, 2023 at 7:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.