实现converter接口方法
自定义转换器类代码如下:
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConvert implements Converter<String, Date> {
@Override
public Date convert(String stringDate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date d = null;
try {
d = simpleDateFormat.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
}
Spring MVC中需要配置如下:
<bean id="dateConvert" class="com.susq.springbegin.utils.DateConvert"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="dateConvert">
<set> <ref bean="stringToDateConverter"/> </set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
也可以实现Formatter,
Formatter是一类特殊的Converter,专门处理字符串的转换
类似于Converter, 修改实现和配置文件即可
public class DateConvert implements Formatter<Date> {
@Override
public Date parse(String s, Locale locale) throws ParseException { S
impleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date d = null;
try {
d = simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
@Override
public String print(Date date, Locale locale) {
return null;
}
}
配置文件如下:
<bean id="dateConvert" class="com.susq.springbegin.utils.DateConvert"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set> <ref bean="dateConvert"/> </set>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
日期转换除了自定义还可以使用注解
@DateTimeFormat(partten="yyyy-MM-dd")