2011-11-23 2 views
2

내가 지금처럼 servletContextin에게 컨트롤러에 액세스하려고하지만, 널 포인터 예외가 계속 해요 : Grails는 2.0의 servletContext

def servletContext = getServletContext() 
def serverPath = servletContext.getRealPath("/") 

... 난 한 번에 단지 최근에 메일 링리스트에 그 문제를 건너했습니다, 그러나 제안 유일한 '적절한'해결 방법은 BootStrap.groovy의 초기화 폐쇄에서 설정하는 것이었다 :

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH 

class BootStrap { 

    def init = { servletContext -> 

     SCH.servletContext = servletContext 
    } 
.... 

가 ...이 여전히 사건입니까? 그 솔루션은 나를 위해 어떤 차이를하지 않았다, 여전히 사전에 NPE

감사

가지고

답변

5

servletContext는 컨트롤러에 당신이 def servletContext를 선언하는 경우 자동으로 주입하는 봄 콩입니다.

홀더 객체가 사라집니다. ServletContext 또는 ApplicationContext를 유지하는 데 권장되는 방법은 grailsApplication 봄 빈을 사용하는 것입니다. grailsApplication (예 : 정적 메소드)에 액세스 할 수없는 경우 고유 한 홀더 클래스를 만들 수 있습니다.

버트 벡크 위 (Burt Beckwith)는 Accessing the GrailsApplication and ApplicationContext from domain classes without holdersCreate your own Grails holder class이라는 주제에 대한 훌륭한 블로그 게시물을 몇 권 적었습니다.

+0

... 흠, 그래서이 시도 : 컨트롤러에 ('/')의 servletContext DEF 데프 P = servletContext.getRealPath을 나는 "널 개체에 대한 방법 getRealPath()를 호출 할 수 없습니다"받을 이유가 될 것이다 ? – vector

+1

servletContext는 로컬 변수가 아닌 필드로 선언되어야합니다. 즉, 조치 클로저/메소드 외부에 선언되어야합니다. – ataylor

+0

.... owwww, 그런 뼈! 감사! – vector