2
votes

I am new to Groovy. I want to update session variables inside a Groovy thread. I can't put real code so I am putting sample code.

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

I am able to access session variable outside of thread, but I am getting the following error for session inside thread

"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."

Any idea how can i use session variable inside thread

2
I guess you are trying this in controller which I do not think would work according to the error message which is pretty much lucid. Instead you can move that logic to service and try. I would rather suggest you use Executor plugin to implement what you are trying to achieve with Thread. - dmahapatro
thank you dmahapatro. i will look into the link you provided - Atul
@dmahapatro, I had used executor plugin and found the same issue while using Tag libs in separate thread, I resolved it by making simple DTO's and pass that to the asynch block. - Umair Saleem

2 Answers

1
votes

Generally you can only access the session from within the scope of a web request handling thread, because you need the request context to know which session to use. A reference to the session property in a Grails controller is actually a Groovy-style call to a getSession() method injected into the class by Grails that dynamically fetches the correct session from the current request.

It may be possible to store a reference to this session in a local variable in the controller action, and then refer to that variable within the Thread.start closure:

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

but I haven't tried this myself.

0
votes

Try adding following in web.xml

<web-app ...>
   <listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
   </listener>
</web-app>

And it not works, you can make a simple DTO (POJO) and pass that to thread.