Grails how to get a request object

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 sent by this error caused only one sentence:

 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 to get a handle to a request object in Grails?
  • How do you know about this? So few people asked this question, it should be documented somewhere or in some example, but I can’t find it.
+6
source share
3 answers

In Grails 3.0, from the 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:
http://docs.grails.org/latest/api/org/grails/web/util/WebUtils.html

Note:
Old codehaus package is outdated.

+12
source

Try the 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() 
+7
source

I expect that you probably got "groovy.lang.MissingPropertyException: there is no such property: RequestContextHolder for class: net.ohds.ReportService" because you did not import "org.springframework.web.context.request". RequestContextHolder "in your ReportService.

The most common place to access the request object is the controller. From the controller, you simply reference the request property and it will be there. See http://grails.org/doc/latest/ref/Controllers/request.html .

The answer to the question of how to access the request object from another location may depend on what is located elsewhere.

UPDATE

I don’t know why you had problems transferring the request from the controller to the service, but you can. I suspect you are calling the method incorrectly, but something like this will work ...

 // grails-app/services/com/demo/HelperService.groovy package com.demo class HelperService { // you don't have to statically type the // argument here... but you can def doSomethingWithRequest(javax.servlet.http.HttpServletRequest req) { // do whatever you want to do with req here... } } 

Controller...

 // grails-app/controllers/com/demo/DemoController.groovy package com.demo class DemoController { def helperService def index() { helperService.doSomethingWithRequest request render 'Success' } } 
+1
source

Source: https://habr.com/ru/post/969569/


All Articles