springMVC相关—类型转换器
数据类型转换
1. 自定义类型转换器实现Converter<S,T>接口并加入到SpringMVC的IOC容器中,
1 /* 2 @Compent加入到ioc容器中 3 数据类型转化器Myconwerter类继承Converter<原类型,目标类型> 4 */ 5 @Component 6 public class MyConverter implements Converter<String, Student>{ 7 @Override 8 public Student convert(String source) { 9 if (source!=null ) { 10 String[] split= source.split("-"); 11 if (split.length==2) { 12 String name=split[0]; 13 Integer gender=Integer.parseInt(split[1]); 14 Student stu=new Student(); 15 stu.setName(name); 16 stu.setGender(gender); 17 return stu; 18 } 19 } 20 return null; 21 } 22 }
1 //要转换成的Student对象类 2 public class Student { 3 private String name; 4 private Integer gender; 5 ....... 6 }
2.配置自定义转换器到FormattingConversionServiceFactoryBean工厂中!
1 <!-- 将Service再作为annotation-driven的一个属性存在! --> 2 <mvc:annotation-driven conversion-service="Service"></mvc:annotation-driven> 3 4 <!-- 配置Service --> 5 <bean id="Service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 6 <property name="converters"> 7 <set> 8 <ref bean="myConverter"/> 9 </set> 10 </property> 11 </bean>