1. 程式人生 > >SpringMVC之繫結引數的型別轉換(Date/Double)

SpringMVC之繫結引數的型別轉換(Date/Double)

一、使用註解式控制器註冊PropertyEditor(針對具體的controller類處理)

        1、使用WebDataBinder進行控制器級別的註冊PropertyEditor(控制器獨享)

Java程式碼  收藏程式碼
  1. @InitBinder  
  2. // 此處的引數也可以是ServletRequestDataBinder型別  
  3. public void initBinder(WebDataBinder binder) throws Exception {  
  4.     // 註冊自定義的屬性編輯器  
  5.     // 1、日期  
  6.     DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"
    );  
  7.     //CustomDateEditor類是系統內部自帶的類  
  8.     CustomDateEditor dateEditor = new CustomDateEditor(df, true);  
  9.     // 表示如果命令物件有Date型別的屬性,將使用該屬性編輯器進行型別轉換  
  10.     binder.registerCustomEditor(Date.class, dateEditor);  
  11.     // 自定義的電話號碼編輯器(和【4.16.1、資料型別轉換】一樣)  
  12.     binder.registerCustomEditor(PhoneNumberModel.class
    new PhoneNumberEditor());  
  13. }  

        備註:轉換物件必須要實現PropertyEditor介面,例如CustomDateEditor類

Java程式碼  收藏程式碼
  1. package org.springframework.beans.propertyeditors;  
  2. import java.beans.PropertyEditorSupport;  
  3. import java.text.DateFormat;  
  4. import java.text.ParseException;  
  5. import java.util.Date;  
  6. import
     org.springframework.util.StringUtils;  
  7. public class CustomDateEditor extends PropertyEditorSupport {  
  8.     private final DateFormat dateFormat;  
  9.     private final boolean allowEmpty;  
  10.     private final int exactDateLength;  
  11.     public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {  
  12.         this.dateFormat = dateFormat;  
  13.         this.allowEmpty = allowEmpty;  
  14.         exactDateLength = -1;  
  15.     }  
  16.     public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {  
  17.         this.dateFormat = dateFormat;  
  18.         this.allowEmpty = allowEmpty;  
  19.         this.exactDateLength = exactDateLength;  
  20.     }  
  21.     public void setAsText(String text) throws IllegalArgumentException {  
  22.         if (allowEmpty && !StringUtils.hasText(text)) {  
  23.             setValue(null);  
  24.         } else {  
  25.             if (text != null && exactDateLength >= 0 && text.length() != exactDateLength)  
  26.                 throw new IllegalArgumentException((new StringBuilder("Could not parse date: it is not exactly")).append(exactDateLength).append("characters long").toString());  
  27.             try {  
  28.                 setValue(dateFormat.parse(text));  
  29.             } catch (ParseException ex) {  
  30.                 throw new IllegalArgumentException((new StringBuilder("Could not parse date: ")).append(ex.getMessage()).toString(), ex);  
  31.             }  
  32.         }  
  33.     }  
  34.     public String getAsText() {  
  35.         Date value = (Date) getValue();  
  36.         return value == null ? "" : dateFormat.format(value);  
  37.     }  
  38. }  

二、使用xml配置實現型別轉換(系統全域性轉換器)

     (1)註冊ConversionService實現和自定義的型別轉換器 

Xml程式碼  收藏程式碼
  1. <!-- ①註冊ConversionService -->  
  2. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">  
  3.     <property name="converters">  
  4.        <list>  
  5.             <bean class="hb.base.convert.DateConverter">  
  6.                 <constructor-arg value="yyyy-MM-dd"/>  
  7.             </bean>  
  8.         </list>  
  9.     </property>  
  10.     <!-- 格式化顯示的配置  
  11.     <property name="formatters">  
  12.         <list>  
  13.             <bean class="hb.base.convert.DateFormatter">  
  14.                 <constructor-arg value="yyyy-MM-dd"/>  
  15.             </bean>  
  16.         </list>  
  17.     </property>  
  18. -->  
  19. </bean>  

    (2)使用 ConfigurableWebBindingInitializer 註冊conversionService

Xml程式碼  收藏程式碼
  1. <!-- ②使用 ConfigurableWebBindingInitializer 註冊conversionService -->  
  2. <bean id="webBindingInitializer"  
  3.     class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">  
  4.     <property name="conversionService" ref="conversionService" />  
  5.     <property name="validator" ref="validator" />  
  6. </bean>  

    (3)註冊ConfigurableWebBindingInitializer 到RequestMappingHandlerAdapter

Xml程式碼  收藏程式碼
  1. <!--Spring3.1開始的註解 HandlerAdapter -->  
  2. <bean  
  3.     class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  4.     <!--執行緒安全的訪問session -->  
  5.     <property name="synchronizeOnSession" value="true" />  
  6.     <property name="webBindingInitializer" ref="webBindingInitializer"/>  
  7. </bean>  

       此時可能有人會問,如果我同時使用 PropertyEditor 和 ConversionService,執行順序是什麼呢?內部首先查詢PropertyEditor 進行型別轉換,如果沒有找到相應的 PropertyEditor 再通過 ConversionService進行轉換。

三、直接重寫WebBindingInitializer(系統全域性轉換器)

      (1)實現WebBindingInitializer介面

package org.nercita.core.web.springmvc;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.core.convert.ConversionService;
import org.springframework.validation.BindingErrorProcessor;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

/**
 * Created by IntelliJ IDEA.
 * Date:
 * Time: 下午2:50.
 */
public class CustomBindInitializer implements WebBindingInitializer {
    private String format = "yyyy-MM-dd";

    private boolean autoGrowNestedPaths = true;

    private boolean directFieldAccess = false;

    private MessageCodesResolver messageCodesResolver;

    private BindingErrorProcessor bindingErrorProcessor;

    private Validator validator;

    private ConversionService conversionService;

    private PropertyEditorRegistrar[] propertyEditorRegistrars;

    public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) {
        this.autoGrowNestedPaths = autoGrowNestedPaths;
    }

    public boolean isAutoGrowNestedPaths() {
        return this.autoGrowNestedPaths;
    }

    public final void setDirectFieldAccess(boolean directFieldAccess) {
        this.directFieldAccess = directFieldAccess;
    }

    public boolean isDirectFieldAccess() {
        return directFieldAccess;
    }

    public final void setMessageCodesResolver(MessageCodesResolver messageCodesResolver) {
        this.messageCodesResolver = messageCodesResolver;
    }

    public final MessageCodesResolver getMessageCodesResolver() {
        return this.messageCodesResolver;
    }

    public final void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) {
        this.bindingErrorProcessor = bindingErrorProcessor;
    }

    public final BindingErrorProcessor getBindingErrorProcessor() {
        return this.bindingErrorProcessor;
    }

    public final void setValidator(Validator validator) {
        this.validator = validator;
    }

    public final Validator getValidator() {
        return this.validator;
    }

    public final void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    public final ConversionService getConversionService() {
        return this.conversionService;
    }

    public final void setPropertyEditorRegistrar(PropertyEditorRegistrar propertyEditorRegistrar) {
        this.propertyEditorRegistrars = new PropertyEditorRegistrar[]{propertyEditorRegistrar};
    }

    public final void setPropertyEditorRegistrars(PropertyEditorRegistrar[] propertyEditorRegistrars) {
        this.propertyEditorRegistrars = propertyEditorRegistrars;
    }

    public final PropertyEditorRegistrar[] getPropertyEditorRegistrars() {
        return this.propertyEditorRegistrars;
    }


    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
        SimpleDateFormat sf = new SimpleDateFormat(format);
        sf.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sf, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
        binder.registerCustomEditor(Short.class, new CustomNumberEditor(Short.class, true));
        binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
        binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
        binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
        if (this.directFieldAccess) {
            binder.initDirectFieldAccess();
        }
        if (this.messageCodesResolver != null) {
            binder.setMessageCodesResolver(this.messageCodesResolver);
        }
        if (this.bindingErrorProcessor != null) {
            binder.setBindingErrorProcessor(this.bindingErrorProcessor);
        }
        if ((this.validator != null) && (binder.getTarget() != null) &&
                (this.validator.supports(binder.getTarget().getClass()))) {
            binder.setValidator(this.validator);
        }
        if (this.conversionService != null) {
            binder.setConversionService(this.conversionService);
        }
        if (this.propertyEditorRegistrars != null)
            for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars)
                propertyEditorRegistrar.registerCustomEditors(binder);
    }

    public void setFormat(String format) {
        this.format = format;
    }
}

      (2)xml配置

	<bean id="handlerAdapter"  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">	
		<property name="messageConverters">
			<list>
				<bean class="org.nercita.core.web.springmvc.StringHttpMessageConverter" />
				<ref bean="msgConverter"/>
			</list>
		</property>
		<property name="webBindingInitializer">
			<bean class="org.nercita.core.web.springmvc.CustomBindInitializer">		   
				 
				<property name="validator" ref="validator" />
				<property name="conversionService" ref="conversionService" /> 
			</bean> 
		</property>
	</bean>