Use Session Variables in Grails Domain Class

If you have tried using a session variable in the domain class of your Grails project, you clearly know that this will not work.

In your domain class, you will need to add the following import statement (this goes at the top of your domain class file, above the class declaration)

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

You will also need to include the following to get the session variables from the server (Tomcat)

def session = RequestContextHolder.currentRequestAttributes().getSession() 

In my instance, I was using the session variable to get a value that was only being used in the session to work with one of my constraints. The session variable did not need to be saved to the database, so I did not create an class member for it. I had to call

.getSession()

from within the custom validator constraint that I created because Grails was trying to use the session variable as part of the domain class.

Updated: 2020-07-15 | Posted: 2012-03-06