简体   繁体   English

如何使用Jooby-HBV验证

[英]How to use jooby-hbv validation

我想使用通过https://jooby.org/doc/hbv/查看的jooby验证,但是我不能使用它

  1. You need to initialise Hibernate Validator in the App class. 您需要在App类中初始化Hibernate Validator
    use(new Hbv(ClassUtils.getClasses("com.package.of.classes.validate")));
  1. Annotate your classes with the validators. 用验证器注释您的班级。 Note these classes have to be in the above package. 注意这些类必须在上面的包中。 Example: 例:
    public class SampleRequest {
        @NotNull
        private Long id;
        @NotBlank
        String name;
        private @NotBlank
        String description;
        private @Min(1)
        double amount;
    }
  1. You can then use a general error handler in the App class. 然后,您可以在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. Or you can manually validate in your service: 或者,您可以在服务中手动验证:
    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());
            }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM