在使用spring mvc中,綁定頁面傳遞時間字符串數據給Date類型是出錯:
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
解決方法一:
1.使對應Controller控制器繼承 extends SimpleFormController
2.重寫initBinder方法
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }
注意SimpleDateFormat日期格式與頁面日期格式要一致!
解決方法二:
Spring3.0以上的SimpleFormController 已經過時了,最新方式是使用@InitBinder注解的方式
在對應的Controller控制器中
@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)); }
