java - 如何使用 jooby-hbv 验证
问题描述
我想使用 jooby 验证我查看了https://jooby.org/doc/hbv/但我不能使用它
解决方案
- 您需要在 App 类中 初始化Hibernate Validator 。
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;
}
- 然后,您可以在 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 {
// ......
}
});
- 或者您可以在您的服务中手动验证:
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());
}
}
推荐阅读
- java - Java“tasklist.exe /fo csv /nh”命令在等待过程中永远加载
- javascript - 如何在 Adobe 的扩展 JavaScript 文件中包含另一个文件
- javascript - React - 如何跟踪 useRef 孩子的变化
- flutter - 颤振在类和构造函数中为无状态小部件转换文本字段代码
- c# - C# HTMLAGILITYPACK 在两个标签之间抓取数据
- php - 上传 base64_encoded 图像从原始大小增加文件大小
- c# - 使用最小起订量更改参数
- vue.js - 在 nuxt 中获取全局 api 数据
- python - 功能选择:尝试查看保留了哪些列时出现 AttributeError
- android - 如何在运行 expo build android 时修复此错误?