关于springMVC参数的绑定

来源:互联网 发布:三亚市网络监管 编辑:程序博客网 时间:2024/05/22 19:57

前面两种方式都需要controller继承该类

第一种 下面看不到的位置是TRUE

第二种方式






第三种

3、使用ConverstionService

Spring3新引入了Converter系统,而ConversionService则是一个Facade类,用来封装底层实现而对外提供便捷的类型转换。所以这里不能重用之间的DateEditor了,不过大致逻辑还是一样的。另外补充说明一下,Converter是处理任意两类型间的转换,而Formatter是处理字符串和另一类型之间的转换的。可以看出来,Formatter是一类特殊的Converter,并且在处理数据绑定时,Formatter比Converter更加合适。所以我们这里就用Formatter来做:

[java] view plain copy
  1. public class DateFormatter implements Formatter<Date> {  
  2.   
  3.     @Override  
  4.     public String print(Date object, Locale locale) {  
  5.         return null;  
  6.     }  
  7.   
  8.     @Override  
  9.     public Date parse(String text, Locale locale) throws ParseException {  
  10.         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  11.         Date date = null;  
  12.         try {  
  13.             date = format.parse(text);  
  14.         } catch (Exception e) {  
  15.             format = new SimpleDateFormat("yyyy-MM-dd");  
  16.             date = format.parse(text);  
  17.         }  
  18.         return date;  
  19.     }  
  20.   
  21. }  

这里我们只写String到Date的逻辑。然后需要将DateFormatter注册到一个ConversionService中,最后再将ConversionService注册到Spring MVC中。

[html] view plain copy
  1. <bean id="conversionService"  
  2.     class="org.springframework.format.support.FormattingConversionServiceFactoryBean">  
  3.     <property name="formatters">  
  4.         <set>  
  5.             <bean class="com.test.common.core.DateFormatter"></bean>  
  6.         </set>  
  7.     </property>  
  8. </bean>  


如果是用<mvc:annotation-driven />的童鞋,那么很简单,只需要:

[html] view plain copy
  1. <mvc:annotation-driven conversion-service="conversionService"/>  


而未使用<mvc:annotation-driven />的童鞋,需要定义一个WebBindingInitializer(或者使用ConfigurableWebBindingInitializer),然后注入到RequestMappingHandlerAdapter中去:

[html] view plain copy
  1. <bean  
  2.     class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  3.     <property name="webBindingInitializer" ref="webBindingInitializer">  
  4.     </property>  
  5. </bean>  
  6.   
  7. <bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">  
  8.     <property name="conversionService" ref="conversionService"></property>  
  9. </bean>  

此时可能有人会问,如果同时使用PropertyEditor和ConversionService,执行顺序是什么呢?内部首先查找PropertyEditor进行类型转换,如果没有找到相应的PropertyEditor再通过ConversionService进行转换。


4、PropertyEditor的自动注册

对了,这里再稍带提一下自动注册PropertyEditor,只需要将JavaBean和JavaBean名称+Editor这两个类放在同一包下,那么JavaBeans的基础结构会自动发现PropertyEditor的类,而无需你手动注册~