SpringMVC 自定义类型转换器

时间:2022-09-11 08:22:14

先准备一个JavaBean(Employee) 一个Handler(SpringMVCTest) 一个converters(EmployeeConverter)

要实现的输入一个字符串转换成一个employee的对象

1.写一个jsp

 <h1>自定义类型的转换器</h1>
<form:form action="testConversionServiceConverer">
<input type="text" name="employee" />
<input type="submit" value="Submit" />
</form:form>

2.写SpringMVCTest

 @Controller
public class SpringMVCTest { @Autowired
private EmployeeDao employeeDao; @RequestMapping(value="/testConversionServiceConverer")
public String testConverter(@RequestParam("employee") Employee employee){
System.out.println("save: "+employee);
employeeDao.save(employee);
return "redirect:/emps";
}
}

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

 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

     <!-- 配置conversionService -->
<!--
1.先配置conversionService
2.在 mvc:annotation-driven 标签 添加conversion-service="conversionService"
-->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<!--employeeConverter EmployeeConverter类的 首字母小写即可 -->
<ref bean="employeeConverter"/>
</set>
</property>
</bean>