SpringMVC学习(六)-自定义类型转换器

xiaoxiao2021-02-28  111

完成实现自定义类型转换器的重点:

1)编写类型转换器

2)配置配置文件(定义转换器)

3)控制层代码

1.定义的类型转换器

package com.springmvc.controller; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.stereotype.Component; import com.springmvc.crud.entiry.Department; import com.springmvc.crud.entiry.Employee; @Component public class EmployeeConverter implements Converter<String,Employee> { @Override public Employee convert(String source) { if(source!=null) { String[] vals=source.split("-"); if(vals!=null&&vals.length==4) { String lastname=vals[0]; String email=vals[1]; Integer gender=Integer.parseInt(vals[2]); Department department=new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee=new Employee(null,lastname,email,gender,department); System.out.println(source+" --convert--"+employee); return employee; } } return null; } }

2.控制层

package com.springmvc.controller; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.stereotype.Component; import com.springmvc.crud.entiry.Department; import com.springmvc.crud.entiry.Employee; @Component public class EmployeeConverter implements Converter<String,Employee> { @Override public Employee convert(String source) { if(source!=null) { String[] vals=source.split("-"); if(vals!=null&&vals.length==4) { String lastname=vals[0]; String email=vals[1]; Integer gender=Integer.parseInt(vals[2]); Department department=new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee=new Employee(null,lastname,email,gender,department); System.out.println(source+" --convert--"+employee); return employee; } } return null; } }

3.配置文件

package com.springmvc.controller; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.stereotype.Component; import com.springmvc.crud.entiry.Department; import com.springmvc.crud.entiry.Employee; @Component public class EmployeeConverter implements Converter<String,Employee> { @Override public Employee convert(String source) { if(source!=null) { String[] vals=source.split("-"); if(vals!=null&&vals.length==4) { String lastname=vals[0]; String email=vals[1]; Integer gender=Integer.parseInt(vals[2]); Department department=new Department(); department.setId(Integer.parseInt(vals[3])); Employee employee=new Employee(null,lastname,email,gender,department); System.out.println(source+" --convert--"+employee); return employee; } } return null; } }

4.jsp页面

<form action="testConversionServiceConverer" method="POST"> <!-- lastname-email-gender-department.id --> Employee:<input type="text" name="employee"/> <input type="submit" value="Submit"/> </form>
转载请注明原文地址: https://www.6miu.com/read-60958.html

最新回复(0)