如何在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但是当相应的请求参数丢失时似乎没有调用它,从而无法应用默认值。
答案 0 :(得分:2)
您也可以这样做:
控制器..
// 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
}
}
注册监听器bean ...
// grails-app/conf/spring/resources.groovy
beans = {
myListener(com.demo.PersonBindingListener) {
configService = ref('myConfigurationService')
}
}
答案 1 :(得分:0)
这里没有足够的信息可以确定最好的事情是什么,但你有几种选择。没有办法告诉该框架,当它创建一个命令对象的实例时,它应该初始化来自某些服务的属性,但你仍然可以使用你的服务来提供帮助。
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...
}
}
我希望有所帮助。
答案 2 :(得分:0)
@ 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)
您也可以在resources.groovy中覆盖ORDER_BY
和PAGE_SIZE
的值。
searchCommandBindingListener(SearchCommandBindingListener) {
ORDER_BY = 'firstName, lastName'
PAGE_SIZE = 41
}