仅将一些属性绑定到grails域对象上?

时间:2011-04-27 15:20:02

标签: hibernate validation grails groovy gorm

我有这样的地图:

['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绑定到某个现有对象上以获取验证,但我该如何做?

4 个答案:

答案 0 :(得分:6)

您可以在控制器内使用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)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您也可以尝试

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

答案 3 :(得分:0)

您还可以使用以下语法:

 content_type = "image/JPEG"
    key = 'uploads/filename.jpg'
    acl = 'public-read'
    bucket = None

    params_raw = create_upload_data(content_type,key,acl,bucket)

    params = { 'policy': params_raw['policy'],'acl':acl,'signature':params_raw['signature'],'key':params_raw['key'],'Content-Type':params_raw['Content-Type'],'AWSAccessKeyId':params_raw['AWSAccessKeyId'],'success_action_status':params_raw['success_action_status'],'file': binary_data}
    r = requests.post(params_raw['form_action'],data=params,files={'file':binary_data})
    return JsonResponse({'request':str(r.text)},safe=False)

Secure Data Binding With Grails

代码清单4 所述