一:需求
将页面上的字符串转换为Employee对象
<form action="${pageContext.request.contextPath }/springmvc/testConverter" method="post">
<!-- 字符串的格式为:GG-gg@csii.com-0-105 -->
Employee : <input type="text" name="employee"/>
<input type="submit"/>
</form>
二:转换类的实现,需要实现Converter<S,T>接口
package com.crud.bean;
import java.util.Date;
public class Employee {
private Integer id;
private String lastName;
private String email;
private int gerder;
private Department department;
//get...set...
}
package com.crud.couverters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import com.crud.bean.Department;
import com.crud.bean.Employee;
@Controller
public class EmployeeCouverter implements Converter<String, Employee> {
@Override
public Employee convert(String source) {
Employee employee = new Employee();
if (!StringUtils.isEmpty(source.trim())) {
//GG-gg@csii.com-0-105
String[] emp = source.split("-");
if (emp != null && emp.length == 4) {
employee.setLastName(emp[0]);
employee.setEmail(emp[1]);
employee.setGerder(Integer.parseInt(emp[2]));
Department department = new Department();
department.setId(Integer.parseInt(emp[3]));
employee.setDepartment(department);;
}
}
System.out.println(source + employee);
return employee;
}
}
三:转换器配置
springMVC配置文件中的配置
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 若还需要使用格式化标签,将此处的实现类换成org.springframework.format.support.FormattingConversionServiceFactoryBean 即可-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="employeeCouverter"/>
</set>
</property>
</bean>