我正在尝试为java.sql.Timestamp实现自定义bean验证,如下所示 -
@Constraint(validatedBy = { DateTimeValidator.class })
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidDateTime {
String format() default "yyyy-MM-dd HH:mm:ss.S";
String message() default "{Invalid timestamp}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
boolean value() default true; }
DateTimeValidator.java的实现
public class DateTimeValidator implements ConstraintValidator<ValidDateTime , Timestamp > {
private String format;
@Override
public void initialize(ValidDateTime validDateTime ) {
format = validDateTime.format(); }
@Override
public boolean isValid(Timestamp value, ConstraintValidatorContext constraintValidatorContext) {
if (value == null) return false;
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
sdf.parse(value.toString());
} catch (Exception e) { return false; }
return true; }}
应用此注释的字段 -
@ValidDateTime(message="Invalid StartDateTime")
protected Timestamp startDateTime;
如果输入值的格式为“2017-10-21T11:11:11”,则此方法正常,但如果我将任何无效值(例如:“TEST_DATE”)作为输入而不是日期传递,则验证器没有被调用,我得到JAXB解析异常。
如何更正此实现以调用所有输入值并验证正确的值?