【问题标题】:Binding only some properties onto a grails domain object?仅将一些属性绑定到 grails 域对象上?
【发布时间】:2011-04-27 15:20:01
【问题描述】:

我有一张这样的地图:

['var1':'property1', 'var2':'3']

还有这样的课程:

class MyClass{
   MyEnum var1
   int var2
   String var3
}
enum MyEnum{
   PROP1( "property1" )
   PROP2( "property2" );

   private final String variable;

   public MyEnum( String variable ){ this.variable = variable }
   public String getVariable(){ return variable }
}

我只想尝试将var1var2 绑定到某个现有对象上以获取验证,但我该怎么做呢?

【问题讨论】:

    标签: hibernate validation grails groovy grails-orm


    【解决方案1】:

    您可以在控制器中使用bindData。此方法具有可选参数,允许您显式声明绑定应包含或排除哪些属性,例如

    def map = ['var1':'property1', 'var2':'3']
    def target = new MyClass()
    
    // using inclusive map
    bindData(target, map, [include:['var1', 'var2']])
    
    // using exclusive map
    bindData(target, this.params, [exclude:['var2']])
    

    如果您想在控制器外部进行这种绑定,请使用org.codehaus.groovy.grails.web.binding.DataBindingUtils 的方法之一,例如

    /**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclud
     * @param filter The prefix to filter by
     *
     * @return A BindingResult or null if it wasn't successful
     */
    public static BindingResult bindObjectToInstance(Object object, Object source, List include, List exclude, String filter) 
    

    这是一个使用此方法执行与上述bindData 的“包含映射”调用相同的绑定的示例

    def map = ['var1':'property1', 'var2':'3']
    def target = new MyClass()
    DataBindingUtils.bindObjectToInstance(target, map, ['var1', 'var2'], [], null)
    

    【讨论】:

    • 一个巨大的警告:如果您分别绑定父对象和容器对象,容器对象上产生的错误不会波及父对象。
    【解决方案2】:

    您可以为此使用bindData 方法,这样您就可以指定要绑定或不绑定的属性。

    【讨论】:

    • 我可以在控制器之外执行此操作吗?
    • 我只在控制器中使用过它,但如果需要,您可能需要检查 DataBindingUtils 和 BindDynamicMethod 类,它们是与 bindData 方法相关的所有事情,看看是否可以在控制器之外使用 bindData。不确定是否已经有内置解决方案或更简单的解决方案。
    【解决方案3】:

    你也可以试试

    Map myClassMap = ['var1':'property1', 'var2':'3']
    //You can use either of the following options
    MyClass myClass = new MyClass(myClassMap) 
    myClass.properties = myClassMap
    

    【讨论】:

    • 这些选项仅适用于 GORM 对象。 POGO 没有采用MapsetProperties(Map map) 方法的构造函数
    【解决方案4】:

    您还可以使用以下语法:

    // update the var1 and var2 properties in the target
    target.properties['var1', 'var2'] = params
    

    Secure Data Binding With Grails代码清单4所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多