首页 > 解决方案 > 如何使用 jooby-hbv 验证

问题描述

我想使用 jooby 验证我查看了https://jooby.org/doc/hbv/但我不能使用它

标签: javavalidationjooby

解决方案


  1. 您需要在 App 类中 初始化Hibernate Validator 。
    use(new Hbv(ClassUtils.getClasses("com.package.of.classes.validate")));
  1. 使用验证器注释您的类。请注意,这些类必须在上述包中。例子:
    public class SampleRequest {
        @NotNull
        private Long id;
        @NotBlank
        String name;
        private @NotBlank
        String description;
        private @Min(1)
        double amount;
    }
  1. 然后,您可以在 App 类中使用通用错误处理程序。
     err((req, rsp, err) -> {
                Throwable cause = err.getCause();
                if (cause instanceof ConstraintViolationException) {
                    Set<ConstraintViolation<?>> constraints = ((ConstraintViolationException) cause)
                            .getConstraintViolations();

                    // handle errors, return error response 
                } else {
                   // ......
                }
            });
  1. 或者您可以在您的服务中手动验证:
    private void validateRequest(SampleRequest sampleRequest) {
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<SampleRequest>> constraintViolations =
                    validator.validate(sampleRequest);
            if (!constraintViolations.isEmpty()) {
                StringBuilder builder = new StringBuilder();
                for (ConstraintViolation<SampleRequest> error : constraintViolations) {
                    logger.error(error.getPropertyPath() + "::" + error.getMessage());
                    builder.append(error.getPropertyPath() + "::" + error.getMessage());
                }
                throw new IllegalArgumentException(builder.toString());
            }
    }

推荐阅读