Using javax validator or spring validator, how to have separate error messages for individual fields of the same type

I currently have a spring boot application and I use javax validator to check POJO. We have an apis application in the application.

My question is : how can I have separate error messages for individual fields of the same type.

Explanation with an example . Regarding the sample code below: If there is no name a1.name, there is a separate error message (ERROR1), and if the name a2.name is missing, there is a separate error message (ERROR2)

My POJO, with javax validator annotation, looks something like this:

public class A{
 @NotNull
 private String name;
 @NotNull
 private String age;
 //..getters and setters
}

public class B{
 @Valid
 private A a1;
 @Valid
 private A a2;
 }

My break controller looks like this:

@RestController
public class Controller1{
 @GetMapping(value="/abc")
 public void api1(@Valid @RequestBody B b){...}
}

, javax @valid annotaion . , spring @Validated , .

+4
1

, Bean .

REST :

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET -d '{"a1":{}, "a2":{}}}' http://localhost:8080/abc

:

{
       "timestamp":"2017-11-10T17:22:07.534+0000",
       "status":400,
       "error":"Bad Request",
       "exception":"org.springframework.web.bind.MethodArgumentNotValidException",
       "errors":[
          {
             "codes":["NotNull.b.a1.name", "NotNull.a1.name", "NotNull.name", "NotNull.java.lang.String", "NotNull"],
             "arguments":[
                {
                   "codes":["b.a1.name", "a1.name" ],
                   "arguments":null,
                   "defaultMessage":"a1.name",
                   "code":"a1.name"
                }
             ],
             "defaultMessage":"may not be null",
             "objectName":"b",
             "field":"a1.name",
             "rejectedValue":null,
             "bindingFailure":false,
             "code":"NotNull"
          },
          {
             "codes":["NotNull.b.a2.age", "NotNull.a2.age", "NotNull.age", "NotNull.java.lang.String", "NotNull"],
             "arguments":[
                {
                   "codes":[ "b.a2.age", "a2.age"],
                   "arguments":null,
                   "defaultMessage":"a2.age",
                   "code":"a2.age"
                }
             ],
             "defaultMessage":"may not be null",
             "objectName":"b",
             "field":"a2.age",
             "rejectedValue":null,
             "bindingFailure":false,
             "code":"NotNull"
          },
          {
             "codes":[ "NotNull.b.a1.age", "NotNull.a1.age", "NotNull.age", "NotNull.java.lang.String", "NotNull"],
             "arguments":[
                {
                   "codes":["b.a1.age", "a1.age"],
                   "arguments":null,
                   "defaultMessage":"a1.age",
                   "code":"a1.age"
                }
             ],
             "defaultMessage":"may not be null",
             "objectName":"b",
             "field":"a1.age",
             "rejectedValue":null,
             "bindingFailure":false,
             "code":"NotNull"
          },
          {
             "codes":["NotNull.b.a2.name", "NotNull.a2.name", "NotNull.name", "NotNull.java.lang.String", "NotNull"],
             "arguments":[
                {
                   "codes":["b.a2.name", "a2.name"],
                   "arguments":null,
                   "defaultMessage":"a2.name",
                   "code":"a2.name"
                }
             ],
             "defaultMessage":"may not be null",
             "objectName":"b",
             "field":"a2.name",
             "rejectedValue":null,
             "bindingFailure":false,
             "code":"NotNull"
          }
       ],
       "message":"Validation failed for object='b'. Error count: 4",
       "path":"/api/profile/abc"
    }

, , , , , , , , : NotNull.b.a1.name.

( REST) ​​ , , .


. Spring. - :

@RestController
public class Controller1 {

    // This assumes that Spring i18n is properly configured
    @Autowired
    private MessageSource messageSource;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Map<String, String> processValidationError(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();

        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError: fieldErrors) {
            String fieldPath = fieldError.getField();
            String messageCode = fieldError.getCode() + "." + fieldPath;
            String validationMessage = messageSource.getMessage(messageCode, new Object[]{fieldError.getRejectedValue()}, Locale.getDefault());

            // add the validation message, for example "NotNull.a1.name" => "a should not be null"
            errors.put(fieldError.getField(), validationMessage);
        }

        return errors;
    } 


    @GetMapping(value="/abc")
    public void api1(@Valid @RequestBody B b){
        //...
    }
}
+1

Source: https://habr.com/ru/post/1688545/


All Articles