为啥要写日期转换器?
springmvc不知道日期的格式,不写日期转换器将会出现日期格式未知,从而报400错误,这也是常见的参数异常错误。
日期转换器实现
1、创建自定义日期转换类,需要实现Converter抽象类
2、自定义日期转换(1、2步的详细代码如下,我解释的也很详细)
package com.xue.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* 定义时间转换器springmvc
* Converter<S, T>
* S:source要转换的源类型
* T:target 要转换成的数据类型
* @author
*
*/
public class MyConvert implements Converter<String, Date> {
@Override
public Date convert(String source) {
Date result = null;
try {
//指定日期的格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//将源数据转为指定日期格式
result = sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
//返回转换后的时间格式日期
return result;
}
}
3、告诉springmvc自己定义的日期格式
在springmvc核心配置文件中声明自定义类
<!-- 配置注解驱动,使用自定义日期转换器 -->
<mvc:annotation-driven conversion-service="myConvert"/>
<!-- 日期转换器 -->
<!-- 定义转换器 -->
<bean id="myConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 自己的写的转换器全路径名 -->
<bean class="com.xue.utils.MyConvert"></bean>
</set>
</property>
</bean>
注意:日期格式出错是一件比较复杂的事情,关键是你不知道是日期参数出错,所以当springmvc遇到400错误,首先考虑参数错误,如果有时间入库操作,此时得考虑日期格式出错,日期转换器就用上了。