国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html
内部邀请码:C8E245J (不写邀请码,没有现金送)
国内私募机构九鼎控股打造,九鼎投资是在全国股份转让系统挂牌的公众公司,股票代码为430719,为中国PE第一股,市值超1000亿元。 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

还是老规矩,开门见山。 我们开发的时候经常会从html,jsp中将参数传到后台,可是经常会遇到的一种情况就是传过来的数据到后台要组装成一种对象的格式,最常见的就是enum类型了。这时候spring提供的@initBinder这个annotation 就发挥了很大的作用。



 

众所周知spring可以自动将request中的数据对应到对象的每个property,会自动的bind 一些simple data (Strings, int, float, etc.) 对应到 你所要求的Object中,可是如果面对复杂的对象,那就需要借助于PropertyEditor 来帮助你完成复杂对象的对应关系,这个借口提供了两个方法,将一个property 转成string getAsText(), 另外一个方法是将string类型的值转成property对应的类型。使用起来也很简单,来个例子:

 

Java代码  收藏代码
  1. @InitBinder  
  2. public void bindingPreparation(WebDataBinder binder) {  
  3.   DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY");  
  4.   CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true);  
  5.   binder.registerCustomEditor(Date.class, orderDateEditor);  
  6. }  

 

这样同样面临一个问题,如果我有两个变量,变量名不一样,处理的规则也不一样,但是他们都是Date.class 类型, 这可怎么破。比如:



 

贴心的spring,提供了一种重载的方法。 for example:

 

Java代码  收藏代码
  1. @InitBinder  
  2. public void bindingPreparation(WebDataBinder binder) {  
  3.   DateFormat dateFormat1 = new SimpleDateFormat("d-MM-yyyy");  
  4.   CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat1, true);  
  5.   DateFormat dateFormat2 = new SimpleDateFormat("MMM d, YYYY");  
  6.   CustomDateEditor shipDateEditor = new CustomDateEditor(dateFormat2, true);  
  7.   binder.registerCustomEditor(Date.class, "orderDate", orderDateEditor);  
  8.   binder.registerCustomEditor(Date.class, "shipDate", shipDateEditor);  
  9. }  

 

 

其实只要为每个变量绑定一个不同的Editor就可以了,对于不同的变量进行不同的处理。这样就能够方便的完成request 和 property 之间的binder了。

 

以上的两个例子仅供抛砖引玉的作用,更多的spring内容还请大家自己不断探索,个人非常喜欢spring,也会不断发表新的spring文章。

 

posted on 2014-09-28 20:42  孤剑  阅读(15736)  评论(1编辑  收藏  举报