方法一:通过@initBinder数据绑定来实现
@RequestMapping(value = "date1.do")
public @ResponseBody String date1(Date date1){
return date1.toString();
}
@InitBinder("date1")
public void initDate1(WebDataBinder binder){
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
}
方法二:实现Converter接口全局配置
MyDateConverter类
public class MyDateConverter implements Converter<String,Date> {
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
xml配置文件
<mvc:annotation-driven conversion-service="myDateConverter"/>
<bean id ="myDateConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.common.MyDateConverter"></bean>
</set>
</property>
</bean>
Test类
@RequestMapping(value = "date2.do")
public @ResponseBody String date2(Date date2){
return date2.toString();
}
方法三:实现Formatter接口
MyDateFormatter类
public class MyDateFormatter implements Formatter<Date> {
public Date parse(String text, Locale locale) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(text);
}
public String print(Date object, Locale locale) {
return null;
}
}
XML全局配置文件
<mvc:annotation-driven conversion-service="MyDateFormatter"/>
<bean id ="MyDateFormatter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="com.common.MyDateFormatter"></bean>
</set>
</property>
</bean>
Test测试类
@RequestMapping(value = "date2.do")
public @ResponseBody String date2(Date date2){
return date2.toString();
}