我想使用jooby验证,我通过https://jooby.org/doc/hbv/查看,但我无法使用它
- 您需要在应用程序类中初始化 Hibernate验证器。
use(new Hbv(ClassUtils.getClasses("com.package.of.classes.validate")));
- 用验证者注释您的课程。请注意,这些课程必须在上面的软件包中。示例:
public class SampleRequest {
@NotNull
private Long id;
@NotBlank
String name;
private @NotBlank
String description;
private @Min(1)
double amount;
}
- 然后,您可以在应用程序类中使用常规错误处理程序。
err((req, rsp, err) -> {
Throwable cause = err.getCause();
if (cause instanceof ConstraintViolationException) {
Set<ConstraintViolation<?>> constraints = ((ConstraintViolationException) cause)
.getConstraintViolations();
// handle errors, return error response
} else {
// ......
}
});
- 或者您可以在服务中手动验证:
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());
}
}