spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type &#

Posted 山高我为峰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type &#相关的知识,希望对你有一定的参考价值。

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

 

以上是关于spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type &#的主要内容,如果未能解决你的问题,请参考以下文章

Dockerized elasticsearch and fscrawler: failed to create elasticsearch client, disable crawler... Co

Spring Boot Failed to load resource: the server responded with a status of 404 ()

Spring Boot之application.properites的failed to convert java.lang.String to java.lang.Integer问题解决

关于出现Failed to instantiate SLF4J LoggerFactory问题原因,解决办法

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:co

Maven中的Spring Boot的web项目报错Failed to configure a DataSource: ‘url‘