2016-01-15 37 views
0

我想定義一個絕對app目錄變量,它可以從控制器中的每一個動作訪問它所在的定義(通常它會在類構造函數)。我想在控制器範圍內只定義一次。我試圖使用beforeInterceptor:servletContext.getRealPath(「/」)在應用程序啓動時拋出一個錯誤在控制器中

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中定義控制器作用域可訪問的絕對路徑變量?

非常感謝,

回答

1

你可以做Holders.getServletContext()那裏,而不是request.getSession().getServletContext()

此外,控制器中的'beforeInterceptors'永遠不會被調用,因爲Grails 3只支持獨立攔截器。

+0

起初您的解決方案沒有奏效,只是簡單地添加「導入grails.util.Holders」使它像魅力一樣工作。謝謝! – iTiger

相關問題