Grails2.0和servletContext

Grails2.0和servletContext,grails,servlets,grails-2.0,Grails,Servlets,Grails 2.0,我正试图在这样的控制器中访问servletContextin,但不断出现空指针异常: def servletContext = getServletContext() def serverPath = servletContext.getRealPath("/") 。。。我最近在邮件列表中遇到过一次这个问题,但唯一“适当”的解决方法是在BootStrap.groovy中的init闭包中设置它: import org.codehaus.groovy.grails.web.context.

我正试图在这样的控制器中访问servletContextin,但不断出现空指针异常:

def servletContext = getServletContext()
def serverPath  = servletContext.getRealPath("/")
。。。我最近在邮件列表中遇到过一次这个问题,但唯一“适当”的解决方法是在BootStrap.groovy中的init闭包中设置它:

   import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH

class BootStrap {

    def init = { servletContext ->

         SCH.servletContext = servletContext
    }
....
。。。还是这样吗?这个解决方案对我没有任何影响,仍然得到了NPE


提前感谢

servletContext
是一个spring bean,如果您在控制器中声明
def servletContext
,它将自动注入

持有者对象正在消失。获得ServletContext或ApplicationContext的推荐方法是通过
grailsApplication
Springbean。对于无法访问
grailsApplication
(例如静态方法)的情况,可以创建自己的holder类


伯特·贝克维思(Burt Beckwith)就以下主题写了几篇很棒的博客文章:和。

。。。嗯,所以我在控制器中尝试了:def servletContext def p=servletContext.getRealPath(“/”),我得到了“不能在null对象上调用方法getRealPath()”,为什么会这样?servletContext必须声明为字段,而不是局部变量,即在操作闭包/方法之外。