码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC 自定义类型转换器

时间:2018-07-01 00:26:59      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:div   versions   mat   core   length   bubuko   pre   one   springmvc   

技术分享图片

 

新建一个自定义转换器

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import com.atguigu.springmvc.crud.entities.Department;
import com.atguigu.springmvc.crud.entities.Employee;

@Component
public class EmployeeConverter implements Converter<String, Employee> {

    @Override
    public Employee convert(String source) {
        if(source != null){
            String [] vals = source.split("-");
            //GG-gg@atguigu.com-0-105
            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;
    }

}

 

配置xml

  <!-- 配置 ConversionService -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="employeeConverter"/>  <!--  自定义的类名,首字母小写 -->
            </set>
        </property>    
    </bean>

  <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 

Spring MVC 自定义类型转换器

标签:div   versions   mat   core   length   bubuko   pre   one   springmvc   

原文地址:https://www.cnblogs.com/eason-d/p/9249034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!