先准备一个JavaBean(Employee) 一个Handler(SpringMVCTest) 一个converters(EmployeeConverter)
要实现的输入一个字符串转换成一个employee的对象
1.写一个jsp
1 <h1>自定义类型的转换器</h1> 2 <form:form action="testConversionServiceConverer"> 3 <input type="text" name="employee" /> 4 <input type="submit" value="Submit" /> 5 </form:form>
2.写SpringMVCTest
1 @Controller 2 public class SpringMVCTest { 3 4 @Autowired 5 private EmployeeDao employeeDao; 6 7 @RequestMapping(value="/testConversionServiceConverer") 8 public String testConverter(@RequestParam("employee") Employee employee){ 9 System.out.println("save: "+employee); 10 employeeDao.save(employee); 11 return "redirect:/emps"; 12 } 13 }
3.写EmployeeConverter
@Component public class EmployeeConverter implements Converter<String, Employee>{ @Override public Employee convert(String source) { if(source != null){ String [] vals = source.split("-"); if(vals !=null && vals.length==4){ String lastName = vals[0]; String email = vals[1]; Integer gender = Integer.parseInt(vals[2]); Department department = new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee = new Employee(null, lastName, email, gender, department); System.out.println(source+"-convert-"+employee); return employee; } } return null; } }
4.进行配置springmvc.xml
1 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> 2 3 4 <!-- 配置conversionService --> 5 <!-- 6 1.先配置conversionService 7 2.在 mvc:annotation-driven 标签 添加conversion-service="conversionService" 8 --> 9 <bean id="conversionService" 10 class="org.springframework.context.support.ConversionServiceFactoryBean"> 11 <property name="converters"> 12 <set> 13 <!--employeeConverter EmployeeConverter类的 首字母小写即可 --> 14 <ref bean="employeeConverter"/> 15 </set> 16 </property> 17 </bean>