Grails,从会话注入/填充带有值的域对象 [英] Grails, injecting/populating domain object with value from session

查看:153
本文介绍了Grails,从会话注入/填充带有值的域对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,很多类都有公司的公司。当应用程序保存对象时,必须填写公司(有验证)。公司也在会议期间。现在,当我想要使用域类作为命令对象时,公司必须已经被填充或者我得到验证错误。在任何验证发生之前,是否有任何方式始终填写公司字段,以便我每次都不需要手动执行。
(我尝试过自定义数据绑定器,但是当请求中没有参数时它不起作用)

解决方案

您可以使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆