一、报错页面:
二、解决方案:
方案一、二、三前提:
(1)jsp页面:
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime" value="<fmt:formatDate value='${item.createtime}' type='date' pattern='yyyy-MM-dd HH:mm:ss'/>" ></td>
</tr>
方案一:
(1)在springmvc.xml中要开启注解适配器:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
(2)对应提交URL的controller类中添加自定义映射字段方法:
/**
* 注册属性编辑器(字符串转日期)
* @param binder
*/
@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));
}
方案二:
(1)对应VO类中的字段添加注解:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createtime;
(2)在springmvc.xml中开启<mvc:annotation-driven>注解:
<mvc:annotation-driven></mvc:annotation-driven>
方案三:
(1)自定义Converter类:
//需要实现Converter接口,这里是将String类型转换成Date类型
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
//实现将字符串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
//如果参数绑定失败返回null
return null;
}
(2)在配置文件中配置注解适配器(方式一)
<!--注解适配器 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
<!-- 自定义webBinder转换器 -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
</bean>
<!-- conversionService -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="com.audrey.springMVC.tools.utils.DateConverter"/>
</list>
</property>
</bean>
(2)在配置文件中配置注解适配器(方式二)
<!--注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!--注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="conversionService"></property>
</bean> -->
<!-- 方式二:自定义Date转化器 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- conversionService -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="com.audrey.springMVC.tools.utils.DateConverter"/>
</list>
</property>
</bean>