Grails get Session and Management in Service class

前端 未结 4 1720
囚心锁ツ
囚心锁ツ 2021-02-04 04:11

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/servi

相关标签:
4条回答
  • 2021-02-04 04:47

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

    0 讨论(0)
  • 2021-02-04 04:52

    This also works

    import grails.web.api.ServletAttributes
    
    @Transactional
    class AuthService implements ServletAttributes {
    
       // session will be available
    
    0 讨论(0)
  • 2021-02-04 05:03

    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)
        }
    }
    
    0 讨论(0)
  • 2021-02-04 05:10

    For new versions (>2.2) of Grails:

    import org.codehaus.groovy.grails.web.util.WebUtils
    
    ....
    HttpServletRequest request = WebUtils.retrieveGrailsWebRequest().currentRequest
    HttpSession session = request.session
    
    0 讨论(0)
提交回复
热议问题