springmvc配置文件
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="top.demo.crud"></context:component-scan>
<!-- 配置默认的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置默认的servlet处理器 ,用于在没有对应映射的控制器方法时 找到静态的资源 -->
<mvc:default-servlet-handler/>
<!-- 配置注解驱动的 类型转换服务的工厂 -->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
<!-- 给容器注入类型转换服务工厂Bean 在属性中添加自定义的转换器 -->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="testConver"/>
</set>
</property>
</bean>
</beans>
实现类型转换接口的自定义转换器类
接上一篇文章的例子
把String类型转换为Employ类型
package top.demo.crud.Conver;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import top.demo.crud.bean.Department;
import top.demo.crud.bean.Employ;
@Component
public class TestConver implements Converter<String,Employ >{
/*
* 自定义的转换器实现Converter接口
* 泛型参数 从什么类型转换到什么类型
*
* */
@Override
public Employ convert(String str) {
//小红----人事部----1
Employ employ=new Employ();
Department department=new Department();
String[] arr=str.split("----");
employ.setName(arr[0]);
department.setDepartmentName(arr[1]);
department.setId(Integer.parseInt(arr[2]));
employ.setDepartment(department);
return employ;
}
}
jsp页面增加了一个表单,表单内只有一个input用于输入规定格式的字符串
且控制器增加一个方法 接收转换后的bean
@RequestMapping("/conver")
public String TestConver(Employ employ) {
employDao.addEmp(employ);
return "showEmp";
}