SpringMVC日期类型转换问题

今天在springmvc开发中碰到一个问题,在访问项目时总是出现404错误,一开始还以为是自己路劲配置错误,再检查过web.xml,controller类之后,发现并没有问题。检查控制台输出信息后发现错误:

Field error in object 'item' on field 'createtime': rejected value [2016-02-03 13:22:53]; codes [typeMismatch.item.createtime,typeMismatch.createtime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.createtime,createtime]; arguments []; default message [createtime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createtime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.util.Date for value '2016-02-03 13:22:53'; nested exception is java.lang.IllegalArgumentException]

jsp:

<tr>
    <td>商品生产日期</td>
    <td><input type="text" name="createtime"value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
</tr>

错误只想Item实体中的createtime字段,查资料后发现原来时前台和后台日期类型转换出错导致的

解决方法:

一:在实体类中加入注解

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createtime;

方法二:在controller中添加数据绑定

	@InitBinder
	public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    dateFormat.setLenient(false);
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	 }
	

方法三:配置全局日期转换器

新建DateConverter.java类

package cn.itcast.springmvc.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;


public class DateConverter implements Converter<String, Date> {    
@Override    
public Date convert(String source) {    
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
    simpleDateFormat.setLenient(false);    
    try {
		return simpleDateFormat.parse(source);
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;    
 	}
}    

配置springmvc.xml

<!-- 注解驱动 -->
	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
	
	<!-- 配置日期转换器 -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">    
        <property name="converters">    
            <list>    
                <bean class="cn.itcast.springmvc.utils.DateConverter" />    
            </list>    
        </property>    
    </bean> 










猜你喜欢

转载自blog.csdn.net/qq_33371372/article/details/80463113