Springmvc入门:自定义数据类型转换
问题描述:表单提交的数据以String类型传递给后台,但类似日期等类型如果格式不对会发生类型转换错误,这时就需要我们自定义数据类型转换
解决办法:创建类实现Converter接口并重写convert()方法,注意实现Converter接口要填写泛型,xxx implements Converter<String,Date>代表把String转换为Date
public Date convert(String s) { if(s == null){ throw new RuntimeException("请您传入数据"); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { return df.parse(s); } catch (Exception e) { throw new RuntimeException("数据类型转换错误"); } }然后在springmvc.xml中配置类型转换器,同时配置springmvc的注解
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.itcast.util.StringToDateConverter"></bean> </set> </property> </bean>
<mvc:annotation-driven conversion-service="conversionService" />重启服务器即可生效