如何使用Jooby-HBV验证



我想使用jooby验证,我通过https://jooby.org/doc/hbv/查看,但我无法使用它

  1. 您需要在应用程序类中初始化 Hibernate验证器
    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. 然后,您可以在应用程序类中使用常规错误处理程序。
     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());
            }
    }

相关内容

  • 没有找到相关文章

最新更新