A)第一种方式:
<!-- 开启注解方式: -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 自定义转换器 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="cn.hd.comverter.DateConverter"></bean>
</list>
</property>
</bean>
2)
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String str) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
B)第二种方式:
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd"), true));
}
/**
* @InitBinder会首先执行,将本类中所有属性是Date类型的,转换成自定义格式
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder){
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
sd.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sd, false));
}