2010-11-24 64 views
4

Grails应用程序中有哪些servletContext?我试图在Config.groovy中访问它,但它不起作用。在视图中访问它也是不可能的。Grails中的servletContext在哪里?

我想设置临时目录作为存储上传文件在我的开发和测试环境storage = (File)servletContext["javax.servlet.context.tempdir"]目录。

继伯特的建议,我试过的conf/Config.groovy中的以下内容:

environments { 
    production { 
     grails.serverURL = "http://demo.com" 
    } 
    development { 
     grails.serverURL = "http://localhost:8080/${appName}" 
     storageDir = org.codehaus.groovy.grails.web.context.ServletContextHolder 
      .getServletContext()["javax.servlet.context.tempdir"] 
    } 
    test { 
     grails.serverURL = "http://localhost:8080/${appName}" 
    } 

} 

...但得到这个错误:

java.lang.NullPointerException: Cannot get property 'javax.servlet.context.tempd 
ir' on null object 
     at Config$_run_closure1_closure4.doCall(Config.groovy:59) 
     at Config$_run_closure1_closure4.doCall(Config.groovy) 
     at Config$_run_closure1.doCall(Config.groovy:57) 
     at Config$_run_closure1.doCall(Config.groovy) 
     at Config.run(Config.groovy:53) 
     at _GrailsPackage_groovy$_run_closure1.doCall(_GrailsPackage_groovy:52) 
     at _GrailsPackage_groovy$_run_closure2_closure10.doCall(_GrailsPackage_g 
roovy:93) 
     at _GrailsPackage_groovy$_run_closure2_closure10.doCall(_GrailsPackage_g 
roovy) 
     at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:2 
80) 
     at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy) 
     at _GrailsPackage_groovy$_run_closure2.doCall(_GrailsPackage_groovy:92) 
     at RunApp$_run_closure1.doCall(RunApp.groovy:28) 
     at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381) 
     at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415) 
     at gant.Gant$_dispatch_closure7.doCall(Gant.groovy) 
     at gant.Gant.withBuildListeners(Gant.groovy:427) 
     at gant.Gant.this$2$withBuildListeners(Gant.groovy) 
     at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source) 
     at gant.Gant.dispatch(Gant.groovy:415) 
     at gant.Gant.this$2$dispatch(Gant.groovy) 
     at gant.Gant.invokeMethod(Gant.groovy) 
     at gant.Gant.executeTargets(Gant.groovy:590) 
     at gant.Gant.executeTargets(Gant.groovy:589) 
Failed to compile configuration file: Cannot get property 'javax.servlet.context 
.tempdir' on null object 

回答

1

你可以从任何CONTROLER访问它。您可能能够从bootstrap.groovy访问它,但我怀疑它。有关从控制器访问它的示例,请参阅 http://www.grails.org/doc/latest/ref/Controllers/servletContext.html

+0

如果你以前需要它,控制器就太迟了,比如在Config中,或者在我的情况下,在resource.groovy中。 – mcv 2011-02-02 11:42:14

2

如果您处于尚未拥有访问权限的代码中,则可以使用org.codehaus.groovy.grails.web.context.ServletContextHolder.getServletContext()

+0

我试过了,但不起作用。见上面的例子。 – deamon 2010-11-25 10:16:07