model類是這樣的
public calss User{ private CorpAddr corpAddr; private String name; }
CorpAddr類是這樣的
public class CorpAddr{ private Date birthday; }
jsp form表單映射
<spring:bind path="user.name"> <input type="text" name="name" /> </spring:bind>
這樣綁定user.name屬性是沒問題的,但用同樣的方式綁定user.corpAddr.birthday卻綁定不上
<spring:bind path="user.corpAddr.birthday"> <input type="text" name="birthday" /> </spring:bind>
這樣綁定不上user.corpAddr.birthday屬性,要使用下面的方式
<spring:bind path="user.corpAddr.birthday"> <input type="text" name="<c:out value='${status.expression}'/>" value="<c:out value='${status.value'/>" /> </spring:bind>
這時候,提交到后台,卻報了個異常,即spring mvc 表單映射日期型字段的問題。
類似這樣的異常
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.控制器繼承 extends SimpleFormController
2.重寫initBinder方法
@InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
binder.registerCustomEditor(Date.class, dateEditor);
super.initBinder(request, binder);
}
注意日期格式串與頁面模式一致
好了,希望對你有用!