spring mvc出現 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endtime'


在使用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));
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM