当控制器的对象通过@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));
}