当我们在从前台向后台提交表单时,如果有时间变量,SpringMVC将会报错:can not cast String to Date;如何解决呢?
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>
</head>
<body>
<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
<!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
<form id="itemForm" action="updateItems" method="post">
<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value='${item.createtime}' type='both'/>"></td>
<tr>
<td>商品图片</td>
<td><c:if test="${item.pic !=null}">
<img src="/pic/${item.pic}" width=100 height=100 />
<br />
</c:if> <input type="file" name="pictureFile" /></td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
如上代码,表单中含有createtime时间字符串,而后台实体类中该字段为Date类型。
方法1:
在Controller中加入如下代码
@InitBinder
public void initBind(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
}
使用该方法,前台时间字符串将会自动转型,但是如果前台传入如2016-06-06 19:20:66 则会报错,必须传入标准的时间字符串。
方法2:
自定义转换类:
package com.hjx.conversion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConveter implements Converter<String, Date> {
@Override
public Date convert(String createtime) {
// 实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
// 转成直接返回
return simpleDateFormat.parse(createtime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 如果参数绑定失败返回null
return null;
}
}
在xml文件中注解驱动加入conversion-service属性,注册自定义转换器
<mvc:annotation-driven conversion-service="dateConveter" />
<!-- 日期转换 全局控制器 -->
<bean id="dateConveter"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.itheima.conversion.DateConveter" />
</list>
</property>
</bean>
好处是该方法特别灵活,如果前台传入2016-06-06 19:20:66 将会自动进位,转换成2016-06-06 19:21:06。