說說Spring中的WebDataBinder


國內私募機構九鼎控股打造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文章。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM