Grails, how to get the request object

grails

Solution

In Grails 3.0, from a service get the `request` object using:

grails-app/services/com/example/MyService.groovy

import org.grails.web.util.WebUtils
...
def request = WebUtils.retrieveGrailsWebRequest().getCurrentRequest()
def ip = request.getRemoteAddr()

Documentation: https://docs.grails.org/latest/api/org/grails/web/util/WebUtils.html#retrieveGrailsWebRequest()

Note: The old `codehaus` package has been deprecated.

Problem

Grails has a request object which is defined here. The problem is when I try to use it, I get: ``` No such property: request for class:xxx ``` Reading the first 100 hits googling this error only produced one suggestion: ``` import javax.servlet.http.HttpServletRequest import org.springframework.web.context.request.ServletRequestAttributes : def my() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); } ``` However, this gives: ``` groovy.lang.MissingPropertyException: No such property: RequestContextHolder for class: net.ohds.ReportService ``` - How does one get a handle on the request object in Grails? - How do you find out about this? So few people have asked this question, it must be documented somewhere, or in some example, but I can't find either.

Original source