先准備一個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>