The main content of this section is to convert a form-submitted string into an object
In the index.jsp:
<span style= "FONT-SIZE:18PX;" ><H2>SPRINGMVC Custom Converters
In the 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>
then, to customize a type converter, the class implements the converter interfacePackage 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//[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]);D epartment department=new Department ();d Epartment.setid ( Integer.parseint (args[3])); Employee E=new employee (NULL, lastName, email, Gender, department); System.out.println (source+ "--conversion--" +e); return e;}} return null;} }
Finally, to configure a springmvc.xml in theConversionservicefactorybean<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>
Learning Springmvc (17) Custom type converters