我正在尝试创建自定义验证器,以仅验证表单中字段的数字。
OnlyNumber.java(注解)
@Target({ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { OnlyNumberValidator.class })
public @interface OnlyNumber {
String message() default "Enter only Numbers";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
OnlyNumberValidator.java(验证器)
public class OnlyNumberValidator implements ConstraintValidator<OnlyNumber, Long> {
@Override
public void initialize(OnlyNumber o) {
}
@Override
public boolean isValid(Long str, ConstraintValidatorContext c) {
System.out.println("Inside OnlyNumberValidator Str "+str);
try
{
//logic goes here
return true;
}
catch (Exception e)
{
return false;
}
}
}
用户.java (Pojo)
@Entity
@Table(name = "user_table")
public class User extends CommonBean {
@IgnoreMe
@Transient
private static final long serialVersionUID = 1L;
@OnlyNumber(message="Role Id Can be Only Number") //Custom Annotation
@Column(name="ROLE_ID")
private Long roleId;
........
}
添加了验证依赖项:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</version>
</dependency>
项目详情: - Spring Boot 1.3.1
当我运行应用程序时,我在 jsp 上收到错误消息,提示无法将类型“java.lang.String”的属性值转换为属性“roleId”所需的类型“java.lang.Long”;嵌套异常是 java.lang.NumberFormatException: For input string: "a"
相反,当我检查登录自定义验证器的 isValid 方法时,我应该收到自定义错误消息Role Id Can be Only Number ,我在该方法中的参数为 null 。
可能是配置有问题或者我遗漏了什么