自定义日期类型转换器:
1.jsp页面:
2.定义一个类:
3.写一个类实现Converter<String,Date>
string,Date原本是S,T,自己改
public class MyConverter implements Converter<String,Date> { public Date convert(String str) { SimpleDateFormat sdf = getDate(str); try { return sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return null; } private SimpleDateFormat getDate(String str) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); if (Pattern.matches("^\d{4}-\d{1,2}-\d{2}$",str)){ sdf=new SimpleDateFormat("yyyy-MM-dd"); } if (Pattern.matches("^\d{4}/\d{1,2}/\d{2}$",str)){ sdf=new SimpleDateFormat("yyyy/MM/dd"); } if (Pattern.matches("^\d{4}\d{1,2}\d{2}$",str)){ sdf=new SimpleDateFormat("yyyyMMdd"); } return sdf; } }
4.配置文件:
<context:component-scan base-package="cn.mvc.t16typeconverter"></context:component-scan> <!--试图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/day03/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--自定义转换器--> <bean id="MyConverter" class="cn.mvc.t16typeconverter.typeconverter.MyConverter"></bean> <!--转换服务--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters" ref="MyConverter"></property> </bean> <!--注解驱动--> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>