本节的主要内容就是将表单提交的字符串转化为对象
在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")
@Controller
public class MyConversion {
@Autowired
private 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;
@Component
public class MyConversionService implements Converter<String,Employee>{
public Employee convert(String source) {
// TODO Auto-generated method stub
//cgf-cgf@sina.com-0-105
if(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>
原文:http://blog.csdn.net/baidu_21578557/article/details/51488355