SpringMVC(六)類型轉換

類型轉換

基本類型轉換
@RequestMapping("primitive")
public @ResponseBody String primitive(@RequestParam Integer value) {
        return "Converted primitive " + value;
}
日期類型轉換
@RequestMapping("date/{value}")
public @ResponseBody String date(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date value) {
    return "Converted date " + value;
}

通過@DateTimeFormat 注解來指定日期轉換參數,可以通過pattern屬性來指定日期格式,或者設置iso來指定日期格式,內置了兩種iso:Date(yyyy-MM-dd),TIME(yyyy-MM-dd HH:mm:ss.SSSZ)。
以上是通過在方法中加注解來轉換日期,如果不加注解會報錯。可以通過配置自定義日期轉換器來全局轉換日期。
首先定義自定義日期轉換器:

package org.springframework.samples.mvc.convert;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;

import java.util.Date;

/**
 * 自定義日期轉換
 * @author yg.huang
 * @version v1.0
 *          DATE  2016/11/24
 */
@Component("customDateConverter")
public class CustomDateConverter implements Converter<String,Date>{

    @Override
    public Date convert(String source) {

        try {
            Date result= DateUtils.parseDate(source,"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss");
            return  result;
        } catch (ParseException e) {
            return null;
        }

    }

}

配置Spring 文件,指定converters屬性后,全局日期轉換器即生效

    <beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <beans:property name="formatters">
            <beans:bean class="org.springframework.samples.mvc.convert.MaskFormatAnnotationFormatterFactory" />
        </beans:property>
        <beans:property name="converters">
            <beans:ref bean="customDateConverter"/>
        </beans:property>
    </beans:bean>

也可以使用@InitBinder在Controller中注冊PeropertyEditor來指定日期轉換格式:

@InitBinder
public void initBinder(WebDataBinder binder) {

    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy@MM@dd@");
        //binder.registerCustomEditor(Date.class,new CustomDateEditor(simpleDateFormat,true));
}

上面的代碼生效后,全局轉換器即失效,當前Controller會使用注冊的PorpertyEditor轉換日期。注意上述代碼在當前Controller每次請求調用一次。

集合類型轉換
@RequestMapping("collection")
public @ResponseBody String collection(@RequestParam Collection<Integer> values) {
    return "Converted collection " + values;
}

請求url:/convert/collection?values=1&values=2&values=3&values=4&values=5和/convert/collection?values=1&values=2,3,4,5 都 可以轉換成Collection

對象類型轉換
@RequestMapping("value")
public @ResponseBody String valueObject(@RequestParam SocialSecurityNumber value) {
        return "Converted value object " + value;
}

在使用了@RequestParam注解后,如果參數類型不是java基本類型,則會調用對象類型轉換器ObjectToObjectConverter將參數轉換成對象。參數類SocialSecurityNumber必須有參數為String的構造器,或者包含靜態的返回類型為當前參數類型的valueOf方法,或者to+參數類型的方法,否則將會報轉換錯誤。ObjectToObjectConverter的代碼如下:

package org.springframework.samples.mvc.convert;

public final class SocialSecurityNumber {

    private final String value;
    
    public SocialSecurityNumber(String value) {
        this.value = value;
    }

    @MaskFormat("###-##-####")
    public String getValue() {
        return value;
    }

    public static SocialSecurityNumber valueOf(@MaskFormat("###-##-####") String value) {
        return new SocialSecurityNumber(value);
    }

}

ObjectToObjectConverter首先會判斷當前類是否包含toXX方法,XX為參數類型(SocialSecurityNumber),如果沒有toXX方法則去找當前是否有工廠方法valueOf,如果還沒有找到,則判斷當前類型是否有參數為String的構造器,如果以上都不滿足,則拋出轉換異常,代碼如下:

@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        Class<?> sourceClass = sourceType.getType();
        Class<?> targetClass = targetType.getType();
        try {
            // Do not invoke a toString() method
            if (String.class != targetClass) {
                Method method = getToMethod(targetClass, sourceClass);
                if (method != null) {
                    ReflectionUtils.makeAccessible(method);
                    return method.invoke(source);
                }
            }

            Method method = getFactoryMethod(targetClass, sourceClass);
            if (method != null) {
                ReflectionUtils.makeAccessible(method);
                return method.invoke(null, source);
            }

            Constructor<?> constructor = getFactoryConstructor(targetClass, sourceClass);
            if (constructor != null) {
                return constructor.newInstance(source);
            }
        }
        catch (InvocationTargetException ex) {
            throw new ConversionFailedException(sourceType, targetType, source, ex.getTargetException());
        }
        catch (Throwable ex) {
            throw new ConversionFailedException(sourceType, targetType, source, ex);
        }

        // If sourceClass is Number and targetClass is Integer, then the following message
        // format should expand to:
        // No toInteger() method exists on java.lang.Number, and no static
        // valueOf/of/from(java.lang.Number) method or Integer(java.lang.Number)
        // constructor exists on java.lang.Integer.
        String message = String.format(
            "No to%3$s() method exists on %1$s, and no static valueOf/of/from(%1$s) method or %3$s(%1$s) constructor exists on %2$s.",
            sourceClass.getName(), targetClass.getName(), targetClass.getSimpleName());

        throw new IllegalStateException(message);
}
private static Method getToMethod(Class<?> targetClass, Class<?> sourceClass) {
        Method method = ClassUtils.getMethodIfAvailable(sourceClass, "to" + targetClass.getSimpleName());
        return (method != null && targetClass.equals(method.getReturnType()) ? method : null);
}
private static Method getFactoryMethod(Class<?> targetClass, Class<?> sourceClass) {
        Method method = ClassUtils.getStaticMethod(targetClass, "valueOf", sourceClass);
        if (method == null) {
            method = ClassUtils.getStaticMethod(targetClass, "of", sourceClass);
            if (method == null) {
                method = ClassUtils.getStaticMethod(targetClass, "from", sourceClass);
            }
        }
        return method;
}

對象類型轉換與數據綁定是區別的。數據綁定是將request參數綁定到javabean的屬性上,javabean的屬性名必須和參數名一樣。對象類型轉換必須由@RequestParam觸發,加上此注解后則不會觸發數據綁定,參數名必須和reqeuest參數一樣。

格式化類型轉換

SpringMVC允許在類型轉換之前先對request參數格式化,格式化完成之后再轉換類型。例如可以將千分符字符串格式化數字,1,000,000 ,格式成1000000。
通過向conversionService注冊格式化工廠

<!-- Only needed because we install custom converters to support the examples in the org.springframewok.samples.mvc.convert package -->
<beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <beans:property name="formatters">
            <beans:bean class="org.springframework.samples.mvc.convert.MaskFormatAnnotationFormatterFactory" />
        </beans:property>
        <beans:property name="converters">
            <beans:ref bean="customDateConverter"/>
        </beans:property>
</beans:bean>

定義格式化工廠,實現AnnotationFormatterFactory指定對使用什么注解的參數生效,實現getParser,getPrinter方法,在這里提供自己的格式處理類。

public class MaskFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<MaskFormat> {

    public Set<Class<?>> getFieldTypes() {
        Set<Class<?>> fieldTypes = new HashSet<Class<?>>(1, 1);
        fieldTypes.add(String.class);
        return fieldTypes;
    }

    public Parser<?> getParser(MaskFormat annotation, Class<?> fieldType) {
        return new MaskFormatter(annotation.value());
    }

    public Printer<?> getPrinter(MaskFormat annotation, Class<?> fieldType) {
        return new MaskFormatter(annotation.value());
}

注冊完成后,只要對參數使用定義的注解SpringMVC就會自動調用格式化工廠格式化參數,使用方法如下:

@RequestMapping("custom")
public @ResponseBody String customConverter(@RequestParam @MaskFormat("###-##-####") String value) {
        return "Converted '" + value + "' with a custom converter";
}

JavaBean 屬性綁定

JavaBean屬性綁定非常簡單,方法中直接定義JavaBean參數即可,只要JavaBean的屬性名和request參數名一樣,就會進行數據綁定。

@RequestMapping("bean")
public @ResponseBody String bean(JavaBean bean) {
        return "Converted " + bean;
}
基本類型綁定

定義對應類型的屬性即可

private Integer primitive;

如下代碼可以將primitive參數綁定到JavaBean上

<a id="primitiveProp" class="textLink" href="<c:url value="/convert/bean?primitive=3" />">Primitive</a>
日期類型綁定

@DateTimeFormat指定日期格式,也可以按照上文說的使用全局日期轉換器,Controller中的@DataBind也可以轉換

@DateTimeFormat(iso=ISO.DATE)
private Date date;
屬性格式化

同參數格式一樣,注冊了參數格式化工廠后,就可以用注解指定需要格式化的屬性。SpringMVC會調用格式化工廠先格式化request參數,再轉換類型。


@MaskFormat("(###) ###-####")
private String masked;
<a id="maskedProp" class="textLink" href="<c:url value="/convert/bean?masked=(205) 333-3333" />">Masked</a>
集合屬性綁定
private List<Integer> list;

可以通過如下方式:

<a id="listProp" class="textLink" href="<c:url value="/convert/bean?list=1&list=2&list=3" />">List Elements</a>

<a id="listProp" class="textLink" href="<c:url value="/convert/bean?list[0]=1&list[1]=2&list[2]=3" />">List Elements</a>

<a id="listProp" class="textLink" href="<c:url value="/convert/bean?list=1,2,3" />">List Elements</a>
日期集合屬性綁定
@DateTimeFormat(iso=ISO.DATE)
private List<Date> formattedList;
<a id="formattedListProp" class="textLink"
href="<c:url value="/convert/bean?formattedList[0]=2010-07-04&formattedList[1]=2011-07-04" />">@Formatted List Elements</a>
Map屬性綁定
// map will auto-grow as its dereferenced e.g. map[key]=value
private Map<Integer, String> map;
<a id="mapProp" class="textLink" href="<c:url value="/convert/bean?map[key1]=apple&map[key2]=pear" />">Map Elements</a>
JavaBean屬性綁定
// nested will be set when it is referenced e.g. nested.foo=value
private NestedBean nested;
<a id="nestedProp" class="textLink" href="<c:url value="/convert/bean?nested.foo=bar&nested.list[0].foo=baz&nested.map[key].list[0].foo=bip" />">Nested</a>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優秀的...
    笨鳥慢飛閱讀 5,678評論 0 4
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,974評論 6 342
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • 業精于勤荒于嬉,行成于思而毀于隨。(韓愈)圈里有句話“互聯網運營是個筐,啥都能裝”。其實這是有很大的誤解,雖然不同...
    三余書社閱讀 2,179評論 0 2