grails - 如何在 groovy 线程中使用 session

标签 grails groovy

我是 Groovy 的新手。我想在 Groovy 线程中更新 session 变量。
我不能放真正的代码,所以我放了示例代码。

public updatename()
    {
        println(session["firstname"]);
        Thread.start
        {
                session["firstname"] = "atul";
                println(session["firstname"]);         
        }
    }

我能够在线程外访问 session 变量,但在线程内的 session 中出现以下错误

"Error java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request."



知道如何在线程内使用 session 变量

最佳答案

通常,您只能从 Web 请求处理线程的范围内访问 session ,因为您需要请求上下文来知道要使用哪个 session 。对 session 的引用Grails Controller 中的属性实际上是对 getSession() 的 Groovy 风格调用。由 Grails 注入(inject)到类中的方法,该方法从当前请求中动态获取正确的 session 。

可以将对该 session 的引用存储在 Controller 操作中的局部变量中,然后在 Thread.start 中引用该变量。关闭:

public updatename()
{
    println(session["firstname"]);
    def theSession = session
    Thread.start
    {
            theSession["firstname"] = "atul";
            println(theSession["firstname"]);         
    }
}

但我自己没有尝试过。

关于grails - 如何在 groovy 线程中使用 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18769750/

相关文章:

maven - 我如何在Groovy项目中使用 cucumber 定义缺少的步骤?

Grails 配置文件返回空对象而不是字符串

grails - 添加Spring Security插件3.1.1后将无法加载Grails 3.2.4应用程序

java - 在 Tomcat 中,正在从引导类加载器加载 java.lang.LinkageError : JAXB 2. 1 API

jenkins - Groovy 中的闭包不捕获外部变量

grails - Grails Gorm MongoDB索引嵌入式字符串映射

groovy - 在编译Groovy类时遇到奇怪的stacktrace

javascript - 如何将JavaScript变量传递给g:remoteFunction的 “update”属性?

sql - 在 Grails 2.3.x 中执行原始 SQL 查询时如何指定备用数据源?

spring - Grails 服务事务行为