自定义的转换器
@Component
public class EmployeeConverter implements Converter<String, Employee> {
@Override
public Employee convert(String src) {
//GG-gg@163.com-106
//zhangsan-zs@163.com-1-105
Employee employee = null;
if (src != null) {
String[] vals = src.split("-");
if (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 = new Employee(null, lastName, email, gender, department);
System.out.println(src + "--->" + employee);
return employee;
}
}
return null;
}
}
web.xml配置
<!-- 这里的配置直接写死了,框架自带的转换器无法加载 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 配置ConversionService -->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- org.springframework.format.support.FormattingConversionServiceFactoryBean -->
<property name="converters">
<set>
<ref bean="employeeConverter"/>
</set>
</property>
</bean>
jsp页面
类型转换器的实现【实现Converter<S, T>接口】
Converter<S, T> S:Source【待转换的对象】T:Target【目标转换对象】
controller中的配置