考虑以下方法:
@RequestMapping(value="/foo", method=RequestMethod.POST)
public void doIt(@Valid PojoRequest request, BindingResult result) throw Exception
{
if(result.hasErrors())
{
throw new Exception(result.getFieldError().getDefaultMessage());
}
}
class PojoRequest {
String int id;
//getter
}
当我使用 String
正确测试此方法时参数,我收到以下错误:
Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'id'; nested exception is java.lang.NumberFormatException: For input string: "abc"
我可以从BindingResult
找到这个数据,但我想做的是向字段本身添加注释,并将错误消息写入注释中。这可能吗?
最佳答案
以一种方式解决,我会很感激其他方式。
这不是一个可读的答案,这实际上是一个黑客行为,请谨慎使用。
我使用自定义 validator 定义了自定义注释:
@Documented
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidIntegerValidator.class)
public @interface ValidInteger {
String message() default "not a valid integer!";
int min() default 1;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class ValidIntegerValidator implements ConstraintValidator<ValidInteger, Object> {
@Override
public void initialize(ValidInteger constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
try {
Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
然后,我更改了 pojo 字段,如下所示:
class PojoRequest {
@ValidInteger(message = "id is faulty")
private Object id;
public int getId() {
return (int) id;
}
public void setStartHour(Object id) {
this.id = id;
}
}
Setter 不是必需的,但如果您定义了 Setter,则应将 Object
作为参数。
这满足了我的需求,但也非常丑陋。更漂亮的解决方案受到赞赏。
关于java - 类型不匹配绑定(bind)错误的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629663/