Grails有一个定义为here的request对象。
问题是当我尝试使用它时,我得到:
No such property: request for class:xxx
阅读谷歌搜索这个错误的前100个点击量只产生了一个建议:
import javax.servlet.http.HttpServletRequest
import org.springframework.web.context.request.ServletRequestAttributes
:
def my() {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
}
但是,这提供了:
groovy.lang.MissingPropertyException: No such property: RequestContextHolder for class: net.ohds.ReportService
,
发布于 2015-05-18 09:36:02
在Grails 3.0中,使用以下命令从服务获取request
对象:
grails-app/services/com/example/MyService.groovy
import org.grails.web.util.WebUtils
...
def request = WebUtils.retrieveGrailsWebRequest().getCurrentRequest()
def ip = request.getRemoteAddr()
文档:
https://docs.grails.org/latest/api/org/grails/web/util/WebUtils.html#retrieveGrailsWebRequest()
注意:
旧的codehaus
包已被弃用。
发布于 2014-05-20 19:58:39
尝试以下代码:
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()
发布于 2014-05-20 18:04:25
因为您没有在ReportService中导入"org.springframework.web.context.request.RequestContextHolder“类,所以我估计您可能会得到"groovy.lang.MissingPropertyException: No got : RequestContextHolder for class: net.ohds.ReportService”。
访问请求对象最常见的地方是在控制器中。在控制器中,您只需引用request
属性,它就会出现在那里。参见http://grails.org/doc/latest/ref/Controllers/request.html。
如何从其他地方访问请求对象的答案可能取决于其他地方是什么。
更新
我不知道为什么您在将请求从控制器传递到服务时遇到问题,但您可以做到。我怀疑你错误地调用了这个方法,但是像这样的东西是可以工作的…
// 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...
}
}
控制器..。
// grails-app/controllers/com/demo/DemoController.groovy
package com.demo
class DemoController {
def helperService
def index() {
helperService.doSomethingWithRequest request
render 'Success'
}
}
https://stackoverflow.com/questions/23756628
复制相似问题