innov83r
innov83r

Reputation: 55

setting session variables in grails 1.3.7

I have a question that will probably have a very simple solution. I'm running grails 1.3.7 and I'm trying to set a session variable like: session["username"] = uName where uName is a value returned from a database query.

The problem I'm having is that the keyword session seems to be not recognized by grails (it's underlined). Further, when I actually try to run the app I get this error: No such property: session for class:.

I don't have any imports, should I?

Upvotes: 0

Views: 4103

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122414

You only have the session variable available to you in controllers, taglibs and GSPs, not in services or domain classes. You can always access it via the thread-local holder, but bear in mind that you only have a session if the current thread is a request handler (i.e. not if it's a background thread):

import org.springframework.web.context.request.RequestContextHolder

def currentRequest = RequestContextHolder.requestAttributes
if(currentRequest) { // we have been called from a web request processing thread
  // currentRequest is an instance of GrailsWebRequest
  currentRequest.session["uName"] = ...
} else {
  // not in a request handler thread, so no session available
}

but it's generally better to keep logic that requires access to the HTTP request in controllers (or taglibs) where you know that you will always have a "current request".

Upvotes: 2

innov83r
innov83r

Reputation: 55

saving session variables have to be done in controllers not domain classes. thanks to @Igor Artamonov for his useful comment.

Upvotes: 0

Related Questions