如何将默认值应用于Grails 2.3中的命令对象?
请注意,当相应的url参数未指定时,我需要从服务中检索这些默认值。
我有以下命令对象作为我的操作
的参数class SearchCommand {
int page
int pageSize // todo: get default from configurationService
String orderBy // todo: get default from configurationService
String search
}
我已经看过@BindUsing,但当相应的请求参数缺失时,它似乎没有被调用,击败了我应用默认值的尝试。
你也可以这样做:
. .一个控制器
// grails-app/controllers/com/demo/DemoController.groovy
package com.demo
class DemoController {
def createPerson(Person p) {
render "First Name: ${p.firstName}, Last Name: ${p.lastName}"
}
}
class Person {
String firstName
String lastName
}
服务……
// grails-app/services/com/demo/MyConfigurationService.groovy
package com.demo
class MyConfigurationService {
def initializePerson(Person p) {
p.firstName = 'Default First Name'
p.lastName = 'Default Last Name'
}
}
绑定监听器…
// src/groovy/com/demo/PersonBindingListener.groovy
package com.demo
import org.grails.databinding.events.DataBindingListenerAdapter
class PersonBindingListener extends DataBindingListenerAdapter {
def configService
Boolean beforeBinding(Object target, Object errors) {
configService.initializePerson target
true
}
boolean supports(Class<?> clazz) {
clazz == Person
}
}
注册listener bean…
// grails-app/conf/spring/resources.groovy
beans = {
myListener(com.demo.PersonBindingListener) {
configService = ref('myConfigurationService')
}
}
这里没有足够的信息来确定最好的做法是什么,但是您有几个选择。没有办法告诉框架,当它创建一个命令对象的实例时,它应该初始化来自某个服务的属性,但是你仍然可以使用你的服务来帮助。
class MyController {
// there is no way to cause co to automatically be
// initialized with values from your service...
def someAction(MyCommand co) {
}
// something like this might help...
def someOtherAction() {
// the service creates an instance of the object
// and initializes values with
def myCommand = someService.createCommand()
// this will do data binding, overriding the default
// values defined by the service with values that are
// included in request params...
bindData myCommand, params
myCommand.validate()
// carry on...
}
}
@Jeff的回答很好。基于这个答案,我选择了一个更简单的解决方案:
考虑到问题中的设置…:
package com.whatevs
import org.grails.databinding.events.DataBindingListenerAdapter
/**
* Binds the SearchCommand defaults
*/
class SearchCommandBindingListener extends DataBindingListenerAdapter{
String ORDER_BY = 'lastName, firstName'
int PAGE_SIZE = 100
Boolean beforeBinding(Object target, Object errors) {
SearchCommand searchCommand = (SearchCommand) target
searchCommand.pageSize = PAGE_SIZE
searchCommand.orderBy = ORDER_BY
true
}
boolean supports(Class<?> clazz) {
clazz == SearchCommand
}
}
和resources.groovy
searchCommandBindingListener(SearchCommandBindingListener)
您可以覆盖资源中的ORDER_BY
和PAGE_SIZE
的值。Groovy也是。
searchCommandBindingListener(SearchCommandBindingListener) {
ORDER_BY = 'firstName, lastName'
PAGE_SIZE = 41
}