遇到java接收前端日期字符串返回到后端Date字段时报错 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date
Field error in object 'user' on field 'birthday': rejected value [2019-06-19]; codes [typeMismatch.user.birthday,
typeMismatch.birthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.
support.DefaultMessageSourceResolvable: codes [user.birthday,birthday]; arguments []; default message [birthday]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthday';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2019-06-19'; nested exception is java.lang.IllegalArgumentException]]
解决方案一:
添加@DateTimeFormat(pattern="yyyy-MM-dd")
注解
private Integer uid;
private String username;
private String password;
private String name;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
private String sex;
解决方案二:
在controller
层配置了@initBinder
自动转换日期类型的字段格式
@InitBinder
protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}