springboot学习记录之使用校验@Validated Date时间类型校验出现String不能转换Date

当控制器的对象通过@Validated注解标注date类型的字段时候,前端在传入123等不符合时间类型的操作时候会出现

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createdTime1'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '1234'; nested exception is java.lang.IllegalArgumentException

这是因为spring在处理转换的时候是捕获异常直接抛出的

如图

所以做一下处理注册一个转换器

import com.sizheng.SuzhengApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * 自定义spring校验的时间格式转换,如果转换不通过将不做报错处理
 */
public class StringToDateConverter extends PropertyEditorSupport {

    public Date convert(String value)  {
        if(StringUtils.isEmpty(value)) {
            return null;
        }
        value = value.trim();
        Date dtDate=null;
        try {
            if( Pattern.matches("^-?\\d+$", value)){
                if(value.length()>11){
                    dtDate=new Date( Long.valueOf(value));
                }else if(value.length()==11){
                    dtDate=new Date( Long.valueOf(value)*1000);
                }
            }else{
                dtDate = dateFormat.parse(value);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            dtDate=null;
        }
        return dtDate;
    }
    private final DateFormat dateFormat;
    private final boolean allowEmpty;
    private final int exactDateLength;

    public StringToDateConverter(DateFormat dateFormat, boolean allowEmpty) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = -1;
    }

    public StringToDateConverter(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = exactDateLength;
    }

    public void setAsText(@Nullable String text) throws IllegalArgumentException {
        if(this.allowEmpty && !StringUtils.hasText(text)) {
            this.setValue((Object)null);
        } else {
            if(text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
                throw new IllegalArgumentException("Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
            }

            this.setValue(convert(text));
        }

    }
    public static void main(String[] args) {
    }
    public String getAsText() {
        Date value = (Date)this.getValue();
        return value != null?this.dateFormat.format(value):"";
    }

}

然后后控制器注册

@InitBinder
protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new StringToDateConverter(dateFormat, false));
}
在Java中,日期类型通常不是直接使用标准的JSR 303/349注解如`@NotNull`或`@NotBlank`来校验是否为空,因为它们主要是针对String类型。对于`Date`类型,你可以选择使用第三方库,比如Hibernate Validator提供的`javax.validation.constraints.Future`、`javax.validation.constraints.Past`等,或者自定义校验器。 如果你想要在Spring MVC中对`Date`类型进行非空校验,可以创建一个自定义注解,例如: ```java import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; @Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NonBlankDateValidator.class) public @interface NonBlankDate { String message() default "The date cannot be null or blank."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; // 可选的属性... } ``` 然后定义一个校验器`NonBlankDateValidator`,检查日期是否为null: ```java import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; import java.util.Date; public class NonBlankDateValidator implements ConstraintValidator<NonBlankDate, Date> { private LocalDate startDate; @Override public void initialize(NonBlankDate constraintAnnotation) { this.startDate = constraintAnnotation.message().equals("The date cannot be before a certain date.") ? LocalDate.now() : LocalDate.ofEpochDay(Long.MIN_VALUE); // 示例中设定为任意最早日期 } @Override public boolean isValid(Date value, ConstraintValidatorContext context) { return value != null && (!startDate.isBefore(LocalDate.from(value))); } } // 在控制器中使用: @PostMapping public ResponseEntity<?> handle(@Valid @NotBlankDate Date dateField, ...) { // ... } ``` 这样,如果提交的`Date`字段为null或小于起始日期校验将会失败并返回错误消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值