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