• @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进去
  • 相关阅读:
    Javascript 创建对象的三种方法及比较【转载+整理】
    Firebug Console Panel 控制台详解【转载+整理】
    解剖 CPU(另)
    解剖 CPU
    关于 URL 编码及 JavaScript 编码函数【转载+整理】
    基于用户投票的 6 个排名算法【转载+整理】
    奥巴马筹款网站的制作过程【转载+整理】
    CentOS 7.0关闭默认firewall防火墙启用iptables防火墙
    mybatis-generator 代码自动生成工具
    Linux中启动和停止jar包的运行
  • 原文地址:https://www.cnblogs.com/chenying99/p/2505144.html
Copyright © 2020-2023  润新知