Grails get Session and Management in Service class
where does RequestContextHolder come from? Its not visible in grails 3.3.8 (in plugin at least)
For new versions (>2.2) of Grails:
import org.codehaus.groovy.grails.web.util.WebUtils
....
HttpServletRequest request = WebUtils.retrieveGrailsWebRequest().currentRequest
HttpSession session = request.session
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)
}
}