①新建一个类,实现Formatter接口:
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;
}
}
②在dispatcher-servlet.xml文件中配置:
<context:component-scan base-package="com" annotation-config="true"/> <mvc:annotation-driven conversion-service="myDateFormatter"/>
<bean id="myDateFormatter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="com.july.common.MyDateFormatter"></bean> </set> </property> </bean>
第二种方法:
①
import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; 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; } }
②
<context:component-scan base-package="com" annotation-config="true"/> <mvc:annotation-driven conversion-service="myDateConverter"/> <bean id="myDateConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.july.common.MyDateConverter"></bean> <bean class="org.springframework.core.convert.support.StringToBooleanConverter"></bean> </set> </property> </bean>
摘录自geely老师