springMVC转换器配置使用

一:需求

       将页面上的字符串转换为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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值