I have a problem with Grails Session. I was thinking about having a Service Class for my session handling. So I created a class called "SessionService" (under grails-app/services/grails/).
class SessionService {
static transactional = true
GrailsWebRequest request = RequestContextHolder.currentRequestAttributes()
GrailsHttpSession session = request.session
def setTestvar(String value) {
if (session != null)
session.setAttribute("sTeststring", value)
}
def getTestvar() {
if (session != null)
session.getAttribute("sTeststring")
}
}
The Problem is now, that I get a Nullpointer-Exception: "Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession.ToString()".
Usage of my Service Class e.g. in a Controller:
class SampleController {
SessionService sessionService
def selectAnything = {
sessionService.setTestvar("test-value")
render(view: "testview")
}
}
What am I'm doing wrong here? Is it the right way? Or do I have to set "session = request.session" in every method?
Hope to get help from you.
Thank you very much in advance.
Cheers,
Marco
You have to do something like
def session = RequestContextHolder.currentRequestAttributes().getSession()
in every method of your service. But it's not clear to me, why you need such a service. You can allways access the session in your Controller like this...
session.someAttribute = "someValue"
Christian