说说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文章。

 

 

猜你喜欢

转载自himichaelchu.iteye.com/blog/2122942