@InitBinder


Customizing WebDataBinder initialization 
To customize request parameter binding with PropertyEditors, etc. via Spring's WebDataBinder, you can either use @InitBinder-annotated methods within your controller or externalize your configuration by providing a custom WebBindingInitializer. 

Customizing data binding with @InitBinder 
Annotating controller methods with @InitBinder allows you to configure web data binding directly within your controller class. @InitBinder identifies methods which initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods. 
Such init-binder methods support all arguments that @RequestMapping supports, except for command/form objects and corresponding validation result objects. Init-binder methods must not have a return value. Thus, they are usually declared as void. Typical arguments include WebDataBinder in combination with WebRequest or java.util.Locale, allowing code to register context-specific editors. 
The following example demonstrates the use of @InitBinder for configuring a CustomDateEditor for all java.util.Date form properties. 
Java代碼    收藏代碼
  1. @Controller  
  2. public class MyFormController {  
  3.   
  4.     @InitBinder  
  5.     public void initBinder(WebDataBinder binder) {  
  6.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
  7.         dateFormat.setLenient(false);  
  8.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, false));  
  9.     }  
  10.   
  11.     // ...  
  12. }  

WebDataBinder是用來綁定請求參數到指定的屬性編輯器,可以繼承WebBindingInitializer來實現一個全部controller共享的dataBiner 
Java代碼    收藏代碼
  1. @Component  
  2. public class CommonBindingInitializer implements WebBindingInitializer {  
  3.   
  4.     public void initBinder(WebDataBinder binder, WebRequest request) {  
  5.         SimpleDateFormat dateFormat = new SimpleDateFormat(ERPUtil.ISO_DATE_MASK);  
  6.         dateFormat.setLenient(false);  
  7.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, true));  
  8.         binder.registerCustomEditor(String.classnew StringTrimmerEditor(false));  
  9.     }  
  10. }  

也可以在某個單獨的contorller里定義一個dataBinder,使用@InitBinder注解就可以實現 

PS:WebDataBinder是用來綁定請求參數到指定的屬性編輯器.由於前台傳到controller里的值是String類型的,當往Model里Set這個值的時候,如果set的這個屬性是個對象,Spring就會去找到對應的EDITOR進行轉換,然后再SET進去


免責聲明!

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



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