问题描述
我正在使用REST API。 我在模型类的属性上使用hibernate.validator @ NotNull / @ NotBlank / @ NotEmpty批注。 没有像“ p”这样的“ message”参数
@NotNull
private String name
然后,如果最终用户未提供name属性的值,则在请求正文中对POST进行说说。
"may not be null"
此错误消息不是用户友好的,并且未指定字段名称。 为了指定哪个字段,它需要添加“消息”属性
@NotNull(message = "Name can not be null")
private String name;
然后就这样来。
"Name can not be null"
这完全满足了我的条件。 但是我正在寻找一种解决方案,我们不需要在所有属性中添加带有该批注的“ message”参数。因为很难维护错误消息的一致性。
我正在尝试创建一些包装类或框架或一些通用的代码流,在命中@NotNull注释后,该代码流应用于该通用代码,在该代码中我们可以使用默认消息+字段名,例如"${fieldName} can not be null or empty"
。这样,我们就可以动态获取属性名称为null的属性,并可以向最终用户提供用户友好的错误消息。
我尝试通过写.properties文件和Java反射来使用message-bundle,如果属性为null,则可以使用该属性的名称,但这不是我想要的。它应该与@ NotNull / NotEmpty / NotBlank注释一起使用。
该信息似乎在运行时可用
我尝试了以下代码。
public Response toResponse(final ValidationException exception) {
if (exception instanceof ConstraintViolationException) {
final ConstraintViolationException cve = (ConstraintViolationException) exception;
StringBuilder msgBuilder = new StringBuilder("Following constraint violations have been detected: ");
for(ConstraintViolation<?> violation: cve.getConstraintViolations()) {
Class<?> annotationType = violation.getConstraintDescriptor().getAnnotation().annotationType();
if (annotationType == org.hibernate.validator.constraints.NotEmpty.class || annotationType == org.hibernate.validator.constraints.NotNull.class) {
msgBuilder.append(violation.getPropertyPath() + violation.getMessage());
}
}
}
}
在这里,我得到violation.getPropertyPath() = createProject.arg2.name
,因此借助正则表达式或任何我可以提取最后一个值的东西,这里是“名称”。并且由于我们没有Name属性上带有注释@NotNull的“ message”参数,因此我们得到violation.getMessage() = may not be null
因此,使用正则表达式(或其他任何东西)后,将会出现完整的错误消息
Following constraint violations have been detected: name may not be null
我不确定,这是好方法吗?任何输入都是最欢迎的。谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)