Grails get Session and Management in Service class

2020-05-23 09:07发布

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

4条回答
等我变得足够好
2楼-- · 2020-05-23 09:29

For new versions (>2.2) of Grails:

import org.codehaus.groovy.grails.web.util.WebUtils

....
HttpServletRequest request = WebUtils.retrieveGrailsWebRequest().currentRequest
HttpSession session = request.session
查看更多
祖国的老花朵
3楼-- · 2020-05-23 09:31

This also works

import grails.web.api.ServletAttributes

@Transactional
class AuthService implements ServletAttributes {

   // session will be available
查看更多
疯言疯语
4楼-- · 2020-05-23 09:40

where does RequestContextHolder come from? Its not visible in grails 3.3.8 (in plugin at least)

查看更多
贼婆χ
5楼-- · 2020-05-23 09:41

Here is some sample code where I'm pulling session data and request data from a service without passing the request or session objects as a parameter to the service.

package beecomplete

import org.codehaus.groovy.grails.web.util.WebUtils

class HelperService {

    public User getCurrentUser() {
        def webUtils = WebUtils.retrieveGrailsWebRequest()
        return User.findById(webUtils.getSession().userid)
    }

    public Object getModelAttribute(String key) {

        def webUtils = WebUtils.retrieveGrailsWebRequest()
        return webUtils.getCurrentRequest().getAttribute(key)
    }
}
查看更多
登录 后发表回答