springgrailscommand-objects

Get ahold of session in command object in Grails


How can I get the session from within a command object?

I have tried:

import org.springframework.security.context.SecurityContextHolder as SCH

class MyCommand {
   def session = RCH.currentRequestAttributes().getSession()
}

This throws

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.


Solution

  • You have an import for Spring Security's SecurityContextHolder but you're using the standard Grails request holder. If you're using the Acegi plugin, then there's a filter that sets the request in a ThreadLocal managed by org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder, so this will work:

    import org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder as SRH
    class MyCommand {
       def someMethod() {
          def session = SRH.request.session
       }
    }
    

    Note that is has to be in a method since the command class will be instantiated one or more times at startup for initialization, so you need to access the session and request only during the execution of an HTTP request