本文共 1069 字,大约阅读时间需要 3 分钟。
在springMVC中如果表单属性的类型是日期类型时,从页面绑定字符串数据会出错,Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'expert.birthdate'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'birthdate': no matching editors or conversion strategy found
在用SpringMVC整合mybatis的时候,在controller中调用service进行保存数据的操作,遇到了Failed to convert from type .lang.String to type java.util.Date for value………这个错误,然后发现有个字段在Entity中的类型是Date的,然后表单传过来的数据时String类型的,这时就会出现这样的问题,类型转换错误!
解决方法
1.控制器继承 extends SimpleFormController
2.重写initBinder方法
要加一个@InitBinder,查了一下资料,貌似是用于初始化数据的时候,进行数据类型转换,把String类型转为Date类型,这样就不会报错了。
在对应的Controller类中加上如下代码,使用注解,就可以解决问题。
//用于初始化数据的时候,进行数据类型转换,把String类型转为Date类型@InitBinderpublic void initBinder(WebDataBinder binder){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
注意SimpleDateFormat日期格式与页面日期格式要一致!
转载地址:http://jjiab.baihongyu.com/