【问题标题】:servletContext.getRealPath("/") throws an error on app startup in controllerservletContext.getRealPath("/") 在控制器中的应用程序启动时引发错误
【发布时间】:2016-04-20 22:58:48
【问题描述】:

我想定义一个绝对应用程序目录变量,它可以从定义它的控制器中的每个操作中访问(通常在类构造函数中完成)。我只想在控制器范围内定义一次。我尝试使用 beforeInterceptor:

class FileResourceController {

    def uploadPath = ""

    def beforeInterceptor = {
        uploadPath = request.getSession().getServletContext().getRealPath("/") + "uploads" 
    }
}

但 uploadPath 最终为空。

只需这样做:

class FileResourceController {

    def uploadPath = request.getSession().getServletContext().getRealPath("/") + "uploads"
}

在应用启动时引发错误。

def uploadPath = request.getSession().getServletContext().getRealPath("/") + "uploads" 放入动作方法中可以正常工作。

如何在 Grails 中定义控制器范围可访问的绝对路径变量?

非常感谢,

【问题讨论】:

    标签: grails-controller grails-3.0


    【解决方案1】:

    您可以在那里使用Holders.getServletContext() 而不是request.getSession().getServletContext()

    此外,控制器中的“beforeInterceptors”永远不会被调用,因为 Grails 3 只支持独立的拦截器。

    【讨论】:

    • 起初您的解决方案没有奏效,但只需添加“import grails.util.Holders”就可以让它像魅力一样工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多