前面的文章我们讲了通过DateTimeFormat注解让springmvc接收date参数,这篇文章,我们讲解下在controller中使用initBinder注解解决springmvc表单提交接收date参数的方法,利用initBinder注解的方式我个人认为不是太好,因为在实际开发中,我的日期字段,可能需要保存的格式不同,一个是yyyy-MM-dd,另一个是yyyy-MM-dd HH:mm:ss。这样的情况,initBinder注解就不适用了。
利用initBinder注解解决表单接收date类型参数的代码如下,在controller方法里面,重写initBinder方法即可,具体代码如下:
@InitBinder protected void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",2); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true),2); }
通过以上代码就解决Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'actionDate'这样的错误了。