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.classnew PhoneNumberEditor());  
  13. }  

 

        备注:转换对象必须要实现PropertyEditor接口,例如CustomDateEditor类

 

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

 

二、使用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>	



 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(spring,mvc)