spring mvc使用过程中关于spring:bind和绑定java.util.Date遇到的问题

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);
    }

注意日期格式串与页面模式一致

好了,希望对你有用!

posted @ 2012-08-16 10:09  风吹倒了蕉  阅读(3099)  评论(1编辑  收藏  举报