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
servletContextis a spring bean that will automatically be injected if you declaredef servletContextin your controller.The holder objects are going away. The recommended way to get a hold of the ServletContext or the ApplicationContext is through the
grailsApplicationspring 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.