Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails, how to get the request object

Tags:

grails

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
  1. How does one get a handle on the request object in Grails?
  2. 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.
like image 784
John Little Avatar asked May 20 '14 09:05

John Little


Video Answer


2 Answers

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.

like image 65
Dem Pilafian Avatar answered Sep 26 '22 09:09

Dem Pilafian


Try following code:

import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
import org.codehaus.groovy.grails.web.util.WebUtils

...

GrailsWebRequest webUtils = WebUtils.retrieveGrailsWebRequest()
def request = webUtils.getCurrentRequest()
like image 30
MKB Avatar answered Sep 24 '22 09:09

MKB