Search code examples
grails-controllergrails-3.0

servletContext.getRealPath("/") throws an error on app startup in controller


I want to define an absolute app directory variable, which is accesible from every action within controller in which it is define (as normally it would be done in class constructor). I want to define it only once in controller scope. I tried to use beforeInterceptor:

class FileResourceController {

    def uploadPath = ""

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

but uploadPath ends up empty.

Simply doing this:

class FileResourceController {

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

throws an error on app startup.

Puting def uploadPath = request.getSession().getServletContext().getRealPath("/") + "uploads" inside an action method works fine.

How can I define controller scope accessible absolute path variable in Grails?

Many thanks,


Solution

  • You can do Holders.getServletContext() there instead of request.getSession().getServletContext().

    Also, 'beforeInterceptors' in the controller is never called, because Grails 3 only supports standalone interceptors.