眾所周知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了。
@InitBinder public void bindingPreparation(WebDataBinder binder) { DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY"); CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true); binder.registerCustomEditor(Date.class, orderDateEditor); }新聞熱點
疑難解答