学习SpringMVC(十七)之自定义类型转换器

来源:互联网 发布:口红保质期 知乎 编辑:程序博客网 时间:2024/06/05 14:09

本节的主要内容就是将表单提交的字符串转化为对象

在index.jsp中:

<span style="font-size:18px;"><h2>SpringMVC 自定义转换器</h2>  <form action="springmvc/testConversion">  Employee:<input type="text" name="employee">  <input type="submit" value="提交">  </form></span>
在Controller中:

<span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.cgf.springmvc.crud.dao.EmployeeDao;import com.cgf.springmvc.crud.entities.Employee;@RequestMapping(value="/springmvc")@Controllerpublic class MyConversion {@Autowiredprivate EmployeeDao employeeDao;@RequestMapping(value="/testConversion")public String testConversion(@RequestParam(value="employee")Employee employee,Map<String,Object> map){employeeDao.save(employee);//map.put("emplists", employeeDao.getAll());return "redirect:list";}}</span>
之后要自定义一个类型转换器,该类要实现Converter接口

package com.cgf.springmvc.conversion;import org.springframework.core.convert.converter.Converter;import org.springframework.stereotype.Component;import com.cgf.springmvc.crud.entities.Department;import com.cgf.springmvc.crud.entities.Employee;@Componentpublic class MyConversionService implements Converter<String,Employee>{public Employee convert(String source) {// TODO Auto-generated method stub//cgf-cgf@sina.com-0-105if(source!=null){String []args=source.split("-");if(args!=null&&args.length==4){String lastName=args[0];String email=args[1];int gender=Integer.parseInt(args[2]);Department department=new Department();department.setId(Integer.parseInt(args[3]));Employee e=new Employee(null, lastName, email, gender, department);System.out.println(source+"--conversion--"+e);return e;}}return null;  }}
最后要在springmvc.xml中配置一个ConversionServiceFactoryBean

<bean name="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><set><ref bean="myConversionService"></ref></set></property>
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>






0 0