類型轉(zhuǎn)換
基本類型轉(zhuǎn)換
@RequestMapping("primitive")
public @ResponseBody String primitive(@RequestParam Integer value) {
return "Converted primitive " + value;
}
日期類型轉(zhuǎn)換
@RequestMapping("date/{value}")
public @ResponseBody String date(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date value) {
return "Converted date " + value;
}
通過@DateTimeFormat
注解來指定日期轉(zhuǎn)換參數(shù)召衔,可以通過pattern屬性來指定日期格式,或者設(shè)置iso來指定日期格式焦辅,內(nèi)置了兩種iso:Date(yyyy-MM-dd),TIME(yyyy-MM-dd HH:mm:ss.SSSZ)。
以上是通過在方法中加注解來轉(zhuǎn)換日期,如果不加注解會(huì)報(bào)錯(cuò)坊罢。可以通過配置自定義日期轉(zhuǎn)換器來全局轉(zhuǎn)換日期擅耽。
首先定義自定義日期轉(zhuǎn)換器:
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;
/**
* 自定義日期轉(zhuǎn)換
* @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屬性后,全局日期轉(zhuǎn)換器即生效
<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中注冊(cè)PeropertyEditor來指定日期轉(zhuǎn)換格式:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy@MM@dd@");
//binder.registerCustomEditor(Date.class,new CustomDateEditor(simpleDateFormat,true));
}
上面的代碼生效后乖仇,全局轉(zhuǎn)換器即失效憾儒,當(dāng)前Controller會(huì)使用注冊(cè)的PorpertyEditor轉(zhuǎn)換日期。注意上述代碼在當(dāng)前Controller每次請(qǐng)求調(diào)用一次乃沙。
集合類型轉(zhuǎn)換
@RequestMapping("collection")
public @ResponseBody String collection(@RequestParam Collection<Integer> values) {
return "Converted collection " + values;
}
請(qǐng)求url:/convert/collection?values=1&values=2&values=3&values=4&values=5和/convert/collection?values=1&values=2,3,4,5 都 可以轉(zhuǎn)換成Collection
對(duì)象類型轉(zhuǎn)換
@RequestMapping("value")
public @ResponseBody String valueObject(@RequestParam SocialSecurityNumber value) {
return "Converted value object " + value;
}
在使用了@RequestParam
注解后起趾,如果參數(shù)類型不是java基本類型,則會(huì)調(diào)用對(duì)象類型轉(zhuǎn)換器ObjectToObjectConverter
將參數(shù)轉(zhuǎn)換成對(duì)象警儒。參數(shù)類SocialSecurityNumber
必須有參數(shù)為String
的構(gòu)造器训裆,或者包含靜態(tài)的返回類型為當(dāng)前參數(shù)類型的valueOf方法,或者to+參數(shù)類型的方法蜀铲,否則將會(huì)報(bào)轉(zhuǎn)換錯(cuò)誤边琉。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
首先會(huì)判斷當(dāng)前類是否包含toXX方法,XX為參數(shù)類型(SocialSecurityNumber
)记劝,如果沒有toXX方法則去找當(dāng)前是否有工廠方法valueOf变姨,如果還沒有找到,則判斷當(dāng)前類型是否有參數(shù)為String
的構(gòu)造器厌丑,如果以上都不滿足定欧,則拋出轉(zhuǎn)換異常别伏,代碼如下:
@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;
}
對(duì)象類型轉(zhuǎn)換與數(shù)據(jù)綁定是區(qū)別的。數(shù)據(jù)綁定是將request參數(shù)綁定到j(luò)avabean的屬性上忧额,javabean的屬性名必須和參數(shù)名一樣厘肮。對(duì)象類型轉(zhuǎn)換必須由@RequestParam
觸發(fā),加上此注解后則不會(huì)觸發(fā)數(shù)據(jù)綁定睦番,參數(shù)名必須和reqeuest參數(shù)一樣类茂。
格式化類型轉(zhuǎn)換
SpringMVC允許在類型轉(zhuǎn)換之前先對(duì)request參數(shù)格式化,格式化完成之后再轉(zhuǎn)換類型托嚣。例如可以將千分符字符串格式化數(shù)字巩检,1,000,000 ,格式成1000000示启。
通過向conversionService注冊(cè)格式化工廠
<!-- 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>
定義格式化工廠兢哭,實(shí)現(xiàn)AnnotationFormatterFactory
指定對(duì)使用什么注解的參數(shù)生效,實(shí)現(xiàn)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());
}
注冊(cè)完成后迟螺,只要對(duì)參數(shù)使用定義的注解SpringMVC就會(huì)自動(dòng)調(diào)用格式化工廠格式化參數(shù),使用方法如下:
@RequestMapping("custom")
public @ResponseBody String customConverter(@RequestParam @MaskFormat("###-##-####") String value) {
return "Converted '" + value + "' with a custom converter";
}
JavaBean 屬性綁定
JavaBean屬性綁定非常簡(jiǎn)單舍咖,方法中直接定義JavaBean參數(shù)即可矩父,只要JavaBean的屬性名和request參數(shù)名一樣,就會(huì)進(jìn)行數(shù)據(jù)綁定排霉。
@RequestMapping("bean")
public @ResponseBody String bean(JavaBean bean) {
return "Converted " + bean;
}
基本類型綁定
定義對(duì)應(yīng)類型的屬性即可
private Integer primitive;
如下代碼可以將primitive參數(shù)綁定到JavaBean上
<a id="primitiveProp" class="textLink" href="<c:url value="/convert/bean?primitive=3" />">Primitive</a>
日期類型綁定
可@DateTimeFormat
指定日期格式窍株,也可以按照上文說的使用全局日期轉(zhuǎn)換器,Controller中的@DataBind
也可以轉(zhuǎn)換
@DateTimeFormat(iso=ISO.DATE)
private Date date;
屬性格式化
同參數(shù)格式一樣攻柠,注冊(cè)了參數(shù)格式化工廠后球订,就可以用注解指定需要格式化的屬性。SpringMVC會(huì)調(diào)用格式化工廠先格式化request參數(shù)瑰钮,再轉(zhuǎn)換類型冒滩。
@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>