仍是老规矩,开门见山。 咱们开发的时候常常会从html,jsp中将参数传到后台,但是常常会遇到的一种状况就是传过来的数据到后台要组装成一种对象的格式,最多见的就是enum类型了。这时候spring提供的@initBinder这个annotation 就发挥了很大的做用。html
众所周知spring能够自动将request中的数据对应到对象的每一个property,会自动的bind 一些simple data (Strings, int, float, etc.) 对应到 你所要求的Object中,但是若是面对复杂的对象,那就须要借助于PropertyEditor 来帮助你完成复杂对象的对应关系,这个借口提供了两个方法,将一个property 转成string getAsText(), 另一个方法是将string类型的值转成property对应的类型。使用起来也很简单,来个例子:java
@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
贴心的spring,提供了一种重载的方法。 for example:jsp
@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了。spa
以上的两个例子仅供抛砖引玉的做用,更多的spring内容还请你们本身不断探索,我的很是喜欢spring,也会不断发表新的spring文章。code