您可以执行以下操作:说这是请求类:
public class DummyRequest { @NotNull private String pre; @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 nulllength may not be nullsomeField may not be nullsomeOtherField may not be nullbreadth may not be null


