SpringMVC (11)_Data conversion of data binding process

       Preface: This article mainly introduces the concepts and usage of data conversion in the data binding process of SpringMVC .

This article focuses on the following issues:

  • SpringMVC built-in converter
  • custom converter

1. Built-in converter

        There are many converters built into the Spring MVC context to do most Java type conversions .

 

Group 1: Scalar Converters

class name description
StringToBooleanConverter String—–>Boolean(true:true/on/yes/1;false:false/off/no/0)
ObjectToStringConverter Object—–>String (call toString method to convert)
StringToNumberConverterFactory String—–>Number (such as Integer, Long, etc.)
NumberToNumberConverterFactory Number subtype <——> Number subtype (Integer, Long, Double, etc.)
StringToCharacterConverter String —–>java.lang.Character takes the first character of the string
NumberToCharacterConverter Number subtypes (Integer, Long, Double, etc.) --> java.lang.Character
CharacterToNumberFactory java.lang.Character ——>Number subtype (Integer, Long, Double, etc.)
StringToEnumConverterFactory String-->enum type (convert the string to the required enum type through Enum.valueOf)
EnumToStringConverter enum type—–>String (returns the name() value of the enum object)
StringToLocaleConverter String—–>java.util.Local
PropertiesToStringConverter java.util.Properties—–>String (defaults to ISO-8859-1 decoding)
StringToPropertiesConverter String—–>java.util.Properties (default decoded by ISO-8859-1)

 

 The second group: collection, array related converters

ArrayToCollectionConverter Any S array --> any T collection (List, Set)
CollectionToArrayConverter Any T collection (List, Set) --> any S array
ArrayToArrayConverter Arbitrary S array <—-> any T array
CollectionToCollectionConverter Any T collection (List, Set) <—-> Any T collection (List, Set), that is, type conversion between collections
MapToMapConverter Conversion between Map<—->Map
ArrayToStringConverter Arbitrary S array --> String type
StringToArrayConverter String—->Array is split by "," by default, and the spaces on both sides of the string are removed (trim)
ArrayToObjectConverter Any S array --> conversion of any Object 
(if the target type is compatible with the source type, the source object is returned directly; otherwise, the first element of the S array is returned and type conversion is performed)
ObjectToArrayConverter Object—–> single-element array
CollectionToStringConverter 任意T集合(List、Set)—->String类型
StringToCollectionConverter String—–>集合(List、Set)(默认通过“,”分割,且去除字符串的两边空格(trim))
CollectionToObjectConverter 任意T集合—->任意Object的转换 
(如果目标类型和源类型兼容,直接返回源对象;否则返回S数组的第一个元素并进行类型转换)
ObjectToCollectionConverter Object—–>单元素集合

 

第三组:默认(fallback)转换器:之前的转换器不能转换时调用

ObjectToObjectConverter Object(S)—–>Object(T)(首先尝试valueOf进行转换、没有则尝试new 构造器(S))
IdToEntityConverter Id(S)—–>Entity(T) 
查找并调用public static T findEntityName获取目标对象,EntityName是T类型的简单类型
FallbackObjectToStringConverter Object—–>String ConversionService 
作为恢复使用,即其他转换器不能转换时调用(执行对象的toString()方法)

 

2 自定义转换器

         ConversionService是Spring类型转换体系的核心接口,可以利用 ConversionServiceFactoryBean在Spring的IOC容器中定义一个ConversionService,Spring 将自动识别出IOC 容器中的ConversionService,并在 Bean属性配置及Spring MVC 处理方法入参绑定等场合使用它进行数据的转换。可通过ConversionServiceFactoryBean的converters属性注册自定义的类型转换器口。

<!-- 配置 ConversionService -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <ref bean="addressConverter"/>
        </set>
    </property>
</bean>

        <mvc:annotation-driven conversion-service=“conversionService”/> 会将自定义的 ConversionService 注册到Spring MVC 的上下文中。

<!-- 开启注解 -->
<mvc:annotation-driven conversion-service="conversionService" />

 

2.1 SpringMVC支持的转化器

        Spring 定义了 3 种类型的转换器接口,实现任意一个转换器接口都可以作为自定义转换器注册到ConversionServiceFactroyBean中:

  1. Converter<S,T>:用于转换S类型到T类型,此接口的实现必须是线程安全的且可以被共享。(后面有此转化器的实例)
  2. GenericConverter 和ConditionalGenericConverter:GenericConverter 接口实现能在多种类型之间进行转换,ConditionalGenericConverter 是有条件的在多种类型之间进行转换。
  3. ConverterFactory:工厂模式的实现,用于选择将一种S源类型转换为R类型的子类型T的转换器的工厂接口。(例如将 String 转换为 Number 及 Number 子类(Integer、Long、Double 等)对象)

2.2 自定义转换器实例

         需求:前台以"江苏-南京"的形式传给后台,后台以实体类接收此信息:

      
         1. 利用Converter<S,T>实现自定义转换器,首先明确S,T的类型,此处自定义转化器将String类型转换为实体类AddressVo,因此S为String,T为AddressVo,先看下实体类:

public class AddressVo {

    private String province;
    private String city;
    
    public AddressVo(String province, String city) {
        this.province = province;
        this.city     = city;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + "]";
    }
}

         2. 然后是转换器:

@Component
public class AddressConverter implements Converter<String, AddressVo> {

    @Override
    public AddressVo convert(String source) {
        if(source != null){
            String [] vals = source.split("-");
            // 江苏-南京
            if(vals != null && vals.length == 2){
                String province = vals[0];
                String city     = vals[1];
                return new AddressVo(province, city);
            }
        }
        return null;
    }

}

         3. 将此转化器注册到ConversionService,正如前面所示。

         自定义转化器就以上三步,比较简单。

 

 

代码下载来源:http://super-wangj.iteye.com/blog/2388430

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326271892&siteId=291194637