grails - Grails-服务可以访问 session 吗?

标签 grails

默认情况下,Grails Service是否可以访问 session 对象?就像能够做到:

session.putSomeValueNeededLater

我问是因为我需要存储一个服务方法导致的变量,而另一服务方法(在同一服务中)以后可能需要存储一个变量,因此我试图避免通过服务中的全局变量来执行此操作一种被认为是不良设计的感觉。因此,我认为 session 可能是另一种方法。谢谢。

编辑:在我的服务中,我遇到以下情况:
masterMethod() {
    call method1()
    call method2()
    //Check if either method 1 or 2 set some variable that indicates whether method 3 needs to be called.
    if (condition == true) { call method3 } // Is it a good idea to store the condition in the session?

}

method 1() { //if some condition, masterMethod() needs to call method 3. Where to store this? In session? }
method 2() { //if some condition, masterMethod() needs to call method 3. Where to store this? In session? }
method 3() {...}

最佳答案

您可以从Grails应用程序中的任何位置访问 session

def session = WebUtils.retrieveGrailsWebRequest().session

即使这可以在服务中使用,您也应该仅从Web层( Controller ,GSP,taglib等)访问 session 。但是,对于您上面描述的特定情况,我根本看不到为什么需要使用 session ,您能做这样的事情吗?
def masterMethod() {
    def method1Result = method1()
    def method2Result = method2()

    method3(method1Result, method2Result)        
}

def method3(method1Result, method2Result) {
    // decide what to do based on the results of methods 1 and 2
}       

关于grails - Grails-服务可以访问 session 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27042791/

相关文章:

javascript - 如何在 Grails Resources Plugin 中指定通配符资源模式?

grails - 在 Ubuntu 上的 STS 下定位 Groovy

unit-testing - 如何模拟从 Controller 测试类注入(inject)域类的服务?

json - grails rest客户将字符串转换为java.util.Date

grails - 是否可以在没有全部内容的情况下使用GSP(常规服务器页面)?

Grails 与 Roo - 为什么 SpringSource 正在插入两种非常相似的技术?

spring - 如何更新Spring Security Management Console?

服务的 Grails Session 范围未按预期工作

grails - grails通过单选按钮设置bean值

Grails Geb : Chrome failed to start