Field error in object 'role' on field 'createDatetime': rejected value [2021-02-19 11:38:38]; codes [typeMismatch.role.createDatetime,typeMismatch.createDatetime,typeMismatch.java.util.Date,typeMismatch];
第一种解决方案:添加注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss"),然后前台以这种方式传递
@ApiModelProperty("创建时间")
@Column
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDatetime;
第二种解决方案:使用 @InitBinder注解,注册一个父类Controller(BaseController),其他Controller去继承它
public class BaseController<T extends IDEntity, ID extends Serializable> {
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new DateEditor());
}
public class DateEditor extends PropertyEditorSupport {
public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void setAsText(String text)
{
setValue(parseString(text));
}
private Object parseString(String text)
{
Date date = null;
if (null != text && !"".equals(text) && !"null".equals(text)) {
try {
String newText = null;
if (text.contains("T") && text.contains("Z")) { // 处理2019-07-07T16:00:00.000Z时间格式
text = text.replace("Z", " UTC");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
Date date1 = sdf.parse(text);
newText = dateFormat.format(date1);
newText = newText + " 00:00:00";
}else if(text.contains("GMT")){
text = text.replace("GMT", "").replaceAll("\\(.*\\)", "");
//将字符串转化为date类型,格式2016-10-12
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss z", Locale.ENGLISH);
date = format.parse(text);
}
if(date == null){
dateTimeFormat.setLenient(false);
if (null != newText) {
date = dateTimeFormat.parse(newText);
} else {
date = dateTimeFormat.parse(text);
}
}
} catch (ParseException e) {
e.printStackTrace();
}
if (date == null) {
try {
dateFormat.setLenient(false);
date = dateFormat.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
return date;
}
}
}
参考来源:https://www.jb51.net/article/117071.htm