Grails,从会话注入/填充带有值的域对象 [英] Grails, injecting/populating domain object with value from session
问题描述
(我尝试过自定义数据绑定器,但是当请求中没有参数时它不起作用)
您可以使用 GORM事件保存,更新或验证对象之前设置属性 beforeInsert
, beforeUpdate
或 beforeValidate
。
在您的域中,您需要这样:
import org .springframework.web.context.request.RequestContextHolder
class Foo {
String company
...
def beforeInsert = {
try {
//添加一些更多的错误检查(即如果没有请求)
def session = RequestContextHolder.currentRequestAttributes()。getSession()
if(session){
this.company = session.company
}
} catch(异常e){
log.error e
}
}
}
In my application many classes have common field 'company'. When application saves that objects, they must be filled with company (there is validation for that). Company is also kept in a session. Now, when I want to use domain class as a command object, company must be already filled or I get validation error. Is there any way to always fill company field, before any validation happens, so that I didn't have to do it manually every time. (I tried custom data binder, but it does not work when there is no parameter in a request)
You could set the property just before the object is saved, updated or validated using the GORM events beforeInsert
, beforeUpdate
or beforeValidate
.
In your domain you need something like that:
import org.springframework.web.context.request.RequestContextHolder
class Foo {
String company
...
def beforeInsert = {
try {
// add some more error checking (i.e. if there is is no request)
def session = RequestContextHolder.currentRequestAttributes().getSession()
if(session) {
this.company = session.company
}
} catch(Exception e) {
log.error e
}
}
}
这篇关于Grails,从会话注入/填充带有值的域对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!