`
朱秋旭
  • 浏览: 228371 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

说说Spring中的WebDataBinder

阅读更多

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



 

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

 

@InitBinder
public void bindingPreparation(WebDataBinder binder) {
  DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY");
  CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true);
  binder.registerCustomEditor(Date.class, orderDateEditor);
}

 

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



 

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

 

@InitBinder
public void bindingPreparation(WebDataBinder binder) {
  DateFormat dateFormat1 = new SimpleDateFormat("d-MM-yyyy");
  CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat1, true);
  DateFormat dateFormat2 = new SimpleDateFormat("MMM d, YYYY");
  CustomDateEditor shipDateEditor = new CustomDateEditor(dateFormat2, true);
  binder.registerCustomEditor(Date.class, "orderDate", orderDateEditor);
  binder.registerCustomEditor(Date.class, "shipDate", shipDateEditor);
}

 

 

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

 

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

 

 
  • 大小: 15.5 KB
  • 大小: 24.3 KB
3
0
分享到:
评论
4 楼 semmy 2014-09-28  
这是旧版本的Spring MVC这样处理,新的SpringMVC应该是用converter接口
3 楼 nuoyan139 2014-09-28  
                                 
2 楼 朱秋旭 2014-09-28  
white_crucifix 写道
前面说的enum后面说的date??

呵呵,是我没有说清楚,前面是我在搞enum 的时候遇到的,后面说date是因为我觉得这个例子很好,一般enum很少同时出现两个吧
1 楼 white_crucifix 2014-09-28  
前面说的enum后面说的date??

相关推荐

Global site tag (gtag.js) - Google Analytics