zoukankan      html  css  js  c++  java
  • 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);
        }

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

    好了,希望对你有用!

  • 相关阅读:
    Unique Binary Search Trees 解答
    Unique Paths II 解答
    Unique Paths 解答
    Maximum Subarray 解答
    Climbing Stairs 解答
    House Robber II 解答
    House Robber 解答
    Valid Palindrome 解答
    Container With Most Water 解答
    Remove Duplicates from Sorted List II 解答
  • 原文地址:https://www.cnblogs.com/dingchenghong/p/2641715.html
Copyright © 2011-2022 走看看