vector
vector

Reputation: 7576

Grails 2.0 and servletContext

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

Upvotes: 2

Views: 3529

Answers (1)

ataylor
ataylor

Reputation: 66069

servletContext is a spring bean that will automatically be injected if you declare def 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 access grailsApplication (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.

Upvotes: 5

Related Questions