Grails 2.0 和 servletContext
我正在尝试像这样在控制器中访问 servletContext,但不断收到空指针异常:
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
提前致谢
I'm trying to access servletContextin a controller like so, but keep getting null pointer exception:
def servletContext = getServletContext()
def serverPath = servletContext.getRealPath("/")
... I've come across that issue on mailing lists once just recently, but the only 'proper' workaround suggested was to set it in the init closure in BootStrap.groovy:
import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
class BootStrap {
def init = { servletContext ->
SCH.servletContext = servletContext
}
....
... is this still the case? That solution didn't make any difference for me, still got NPE
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
servletContext
是一个 spring bean,如果您在控制器中声明def servletContext
,它将自动注入。持有者对象正在消失。获取 ServletContext 或 ApplicationContext 的推荐方法是通过 grailsApplication spring bean。对于无法访问
grailsApplication
(例如静态方法)的情况,您可以创建自己的持有者类。Burt Beckwith 写了几篇关于该主题的精彩博客文章:在没有持有者的情况下从域类访问 GrailsApplication 和 ApplicationContext 和创建您自己的 Grails 持有者类。
servletContext
is a spring bean that will automatically be injected if you declaredef servletContext
in your controller.The holder objects are going away. The recommended way to get a hold of the ServletContext or the ApplicationContext is through the
grailsApplication
spring bean. For situations where you can't accessgrailsApplication
(e.g. static methods), you can create your own holder classes.Burt Beckwith wrote up a couple of great blog posts on the topic: Accessing the GrailsApplication and ApplicationContext from domain classes without holders and Create your own Grails holder class.