Spring MVC Enum 参数转换

2016/01/01 Java

Spring MVC 默认转换成枚举参数时,必须使用枚举的字面量,而且必须区分大小写,如果想传入其他值来转换为枚举参数必须自定义转换器。

示例

package com.fang.online.manager.param;


import com.fang.online.xf.api.enums.IntValueEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @author cyh
 * @Description: 字符串 转 IntVlaueEnum,  字符串可以是 IntVlaueEnum.value IntVlaueEnum.name
 * @date 2016/9/28
 */
public class StringToIntValueEnumConverterFactory implements ConverterFactory<String, IntValueEnum> {

    public <T extends IntValueEnum> Converter<String, T> getConverter(Class<T> targetType) {
        if(!targetType.isEnum()) {
            throw new UnsupportedOperationException("只支持转换到枚举类型");
        }
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends IntValueEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        public T convert(String source) {
            if (source.length() == 0) {
                // It's an empty enum identifier: reset the enum value to null.
                return null;
            }
            try {
                Integer v = Integer.valueOf(source);
                T[] all = enumType.getEnumConstants();
                for(T t:all) {
                    if(t.getValue() == v) return t;
                }
                return null;
            } catch (NumberFormatException e) {
                T[] all = enumType.getEnumConstants();
                for(T t:all) {
                    if(source.equals(t.getName())) return t;
                }
                return null;
            }
        }
    }

}
    <!-- 支持fastJson -->
    <mvc:annotation-driven conversion-service="conversionService">
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteNullStringAsEmpty</value>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.fang.online.manager.param.StringToIntValueEnumConverterFactory"></bean>
            </set>
        </property>
    </bean>

Search

    Table of Contents