SpringMVC Failed to convert from type java.lang.String to type java.util.Date for value '2014-12-02'

来源:互联网 发布:怎么区分中日韩 知乎 编辑:程序博客网 时间:2024/05/10 19:26

          楼主最近在用Spring-SpringMVC-Mybatis做一个网站由于是小白经常遇到各种各样的稀奇古怪的问题,本着程序员的天职就是发现问题然后解决问题,在解决BUG的同时自身的能力也或多或少的得到提高,在做项目的遇到问题的时候也经常式查看CSDN上大牛的博客才解决问题的。这次一个小问题困扰啦好久,今天总算是解决啦。在CSDN 没找到实在其他博客上看到的顺便借花献佛,希望能帮到大家。

       问题是这样的某码农在写web的一个信息录入的页面,前端html页面把一些数据做成表单发给后台 后台储存到数据库中。但在提交表单的时候,老是报错,但 只是前台页面出错,根本没涉及到后台,后台设置啦多个断点 deBUG无数次 ,但不幸的是每次都跟石沉大海一般,程序跟本就没运行到断点处就已经GG啦。刚开始以为是js提交表单出问题 然后各种花式提交表单方法 ,测试啦一两天 都没找到问题的根源。后来某码农准备换个思路从后台源码往前台开始找问题,终于黄天不负有心人,原来是SpringMVC在整合mybatis的时候出现问题。这可能是SpringMVC的一个缺陷(某小白自以为),原因是什么呢?原因是楼主传入的数据中有日期Date这个数据,原来SpringMVC中前台传入的url中HTTP 会解析出数据,但这些数据都是已字符串和其他格式解析出来,但没有Date类型的。所以一个日期类型的数据:2016-06-06后台读到的是个这样的字符串。数据类型不对,后台方法就直接被拦截下来啦。


myeclipse提示错误信息:

Field error in object 'appliedProject' on field 'acceptanceDate': rejected value [2014-12-02]; codes [typeMismatch.appliedProject.acceptanceDate,typeMismatch.acceptanceDate,typeMismatch.java.util.Date,typeMismatch];arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [appliedProject.acceptanceDate,acceptanceDate]; arguments []; default message [acceptanceDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'acceptanceDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2014-12-02'; nested exception is java.lang.IllegalArgumentException]
Field error in object 'appliedProject' on field 'applydate': rejected value [2014-12-02]; codes [typeMismatch.appliedProject.applydate,typeMismatch.applydate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [appliedProject.applydate,applydate]; arguments []; default message [applydate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'applydate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2014-12-02'; nested exception is java.lang.IllegalArgumentException]
Field error in object 'appliedProject' on field 'constructionDate': rejected value [2014-12-02]; codes [typeMismatch.appliedProject.constructionDate,typeMismatch.constructionDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [appliedProject.constructionDate,constructionDate]; arguments []; default message [constructionDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'constructionDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2014-12-02'; nested exception is java.lang.IllegalArgumentException]


      怎么解决:SpringMVC注解@initbinder解决类型转换问题 。表单中的日期字符串和JavaBean的Date类型的转换,而SpringMVC默认不支持这个格式的转换,所以需要手动配置,自定义数据的绑定才能解决这个问题。在需要日期转换的Controller中使用SpringMVC的注解@initbinder和Spring自带的WebDateBinder类来操作。
WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。
代码如下:
@InitBinder  
public void initBinder(WebDataBinder binder) {  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    dateFormat.setLenient(false);  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
}
需要在SpringMVC的配置文件加上
<!-- 解析器注册 -->  
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
    <property name="messageConverters">  
        <list>  
            <ref bean="stringHttpMessageConverter"/>  
        </list>  
    </property>  
</bean>  
<!-- String类型解析器,允许直接返回String类型的消息 -->  
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
换种写法
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
拓展:
spring mvc在绑定表单之前,都会先注册这些编辑器,Spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
使用时候调用WebDataBinder的registerCustomEditor方法
registerCustomEditor源码:
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
    getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
}
第一个参数requiredType是需要转化的类型。
第二个参数PropertyEditor是属性编辑器,它是个接口,以上提到的如CustomDateEditor等都是继承了实现了这个接口的PropertyEditorSupport类。
我们也可以不使用他们自带的这些编辑器类。
我们可以自己构造:
import org.springframework.beans.propertyeditors.PropertiesEditor;

public class DoubleEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || text.equals("")) {
            text = "0";
        }
        setValue(Double.parseDouble(text));
    }

    @Override
    public String getAsText() {
        return getValue().toString();
    }
}

0 0
原创粉丝点击