springmvc----自定义类型转换器----笔记

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";
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值