学习SpringMVC(十七)之自定义类型转换器
Posted 奔跑着的国风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习SpringMVC(十七)之自定义类型转换器相关的知识,希望对你有一定的参考价值。
本节的主要内容就是将表单提交的字符串转化为对象
在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 //[email protected] 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>
以上是关于学习SpringMVC(十七)之自定义类型转换器的主要内容,如果未能解决你的问题,请参考以下文章
[死磕 Spring 35/43] --- IOC 之自定义类型转换器
[死磕 Spring 35/43] --- IOC 之自定义类型转换器