表单提交后台直接将字符串转成日期类型

表单提交中,可以使用 jQuery 序列化表单 serialize()的方法,后台可以直接使用实体类进行接收。

但问题是提交的数据是字符串,如果实体类中有date类型的数据就会报错

ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] 

此时,只要在Controller中加入

@InitBinder
public void initBinder(WebDataBinder binder) {
   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   dateFormat.setLenient(false);
   binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

字符串就可以直接转换成date类型被实体类接收啦,需要修改你提交字符串的格式哦  我的提交格式是

        yyyy-MM-dd HH:mm:ss


猜你喜欢

转载自blog.csdn.net/liuxiaochang_2011/article/details/80504355