一尘不染

如何在Spring Boot中验证JSON请求?

spring-boot

我想验证从客户端收到的JSON请求。我尝试使用批注(@notnull, @length(min=1,max=8),等等。),它工作正常,但问题是我无法获取如果无效的字段和消息将被调用。虽然,我在控制台中收到一条错误消息。

违反约束的列表:

[
  ConstraintViolationImpl
  {
    interpolatedMessage=
    'must be greater than or equal to 900000000',
    propertyPath=phoneNumber,
    rootBeanClass=class
    com.org.infy.prime.RestWithJPA.CarrierFile,
    messageTemplate=
    '{javax.validation.constraints.Min.message}'
  }
  ConstraintViolationImpl
  {
    interpolatedMessage=
    'length must be between 1 and 20',
    propertyPath=accountID,
    rootBeanClass=class
    com.org.infy.prime.RestWithJPA.CarrierFile,
    messageTemplate=
    '{org.hibernate.validator.constraints.Length.message}'
  }
]

询问是否有人可以帮助我,或者给我至少一种选择,以更有效的方式验证请求。

PS: 我不想逐个字段对其进行验证。


阅读 317

收藏
2020-05-30

共1个答案

一尘不染

您可以执行以下操作:说这是请求类:

public class DummyRequest {

    @NotNull
    private String  code;

    @NotNull
    private String  someField;

    @NotNull
    private String  someOtherField;

    @NotNull
    private Double  length;

    @NotNull
    private Double  breadth;

    @NotNull
    private Double  height;

    // getters and setters
}

然后,您可以编写自己的通用validate方法,该方法将给出“不太冗长”的约束违反消息,如下所示:

public static <T> List<String> validate (T input) {
    List<String> errors = new ArrayList<>();
    Set<ConstraintViolation<T>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(input);
    if (violations.size() > 0) {
        for (ConstraintViolation<T> violation : violations) {
            errors.add(violation.getPropertyPath() + " " + violation.getMessage());
        }
    }
    return errors;
}

现在,您可以验证并检查您的请求是否包含任何错误。如果是,则可以打印它(或发送回无效的请求消息)。

public static void main (String[] args) {
    DummyRequest request = new DummyRequest();
    request.setCode("Dummy Value");
    List<String> validateMessages = validate(request);
    if (validateMessages.size() > 0 ) {
        for (String validateMessage: validateMessages) {
            System.out.println(validateMessage);
        }
    }
}


Output:
--------
height may not be null
length may not be null
someField may not be null
someOtherField may not be null
breadth may not be null
2020-05-30