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