在SpringMVC中封装了许多常见类型转换器,所以我们可以很方便的使用-例如,提交表单如果与实体类对象属性值相对应,那么可以直接将参数设置为该实体类对象,那么SpringMVC会自动将提交表单数据转换为实体类对象。
下面演示自定义数据类型转换器。
步骤:
例子:实体类对象有
Employee: id (int), lastName (String) ,email (String), gender(Integer), department (Department)
Department: id(int), departmentName (String)
实现提交数据为 : xx-xx-xx-xx-xx 例 zzh-zzh@163.com-1-106
转换后: lastName: zzh, email: zzh@163.com, gender:1, department: id=106,departmentName=xxx
1、定义一个转换器类 - 实现Converter<S,T>接口,S - 数据原类型,T - 转换后类型。
@Component
public class MyConversion implements Converter<String, Employee> {
@Override
public Employee convert(String source) {
if (source != null) {
String[] vals = source.split("-");
if (vals != null) {
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(0, lastName, email, gender, department);
return employee;
}
}
return null;
}
}
2、在springmvc.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.yyl"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 自动判断请求类型,不会拦截静态资源 -->
<mvc:default-servlet-handler/>
<!---------------------------------------------------------------------------------->
<!-- 1.注册ConversionServiceFactoryBean。
2.将自己所写的转换器注入converters属性中,注意是set类型。
3.在注册驱动标签内的 conversion-service 设为 配置的ConversionServiceFactoryBean
-->
<!-- 注册驱动 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 配置ConversionService -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="myConversion" />
</set>
</property>
</bean>
</beans>