bean-validation – 使用javax验证器或spring验证器如何为相同类型的单独字段分别生成错误消息

目前我有一个
spring启动应用程序和POJO验证我正在使用
javax验证器.我们在应用程序中有rest apis.

我的问题是:如何为相同类型的单独字段分别显示错误消息.

示例说明:参考下面的示例代码:如果a1.name不存在则有单独的错误消息(ERROR1),如果a2.name不存在则有单独的错误消息(ERROR2)

我的POJO,使用javax验证器注释看起来像:

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;
 }

我的休息控制器看起来像:

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

我试图使用组但javax @valid annotaion不支持组.
我尝试使用spring @Validated注释的另一个选项,但问题是它不能应用于字段.

最佳答案 据我所知,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){
        //...
    }
}
点赞