2011-11-08 34 views
2

我試圖在JSP頁面中獲取應用程序上下文。 我在JSP中有以下scriptlet。JSP中的Spring null應用程序上下文

 WebApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); 
     MyClass myClass = (MyClass)(appCtx.getBean("myClass")); 

當使用這個應用程序上下文時會引發空指針異常。 我在這裏做錯了什麼? 我沒有application-context.xml文件,因爲我不需要它。我有通常的處理程序映射的dispatcher-servlet.xml。

另外,作爲附加信息: 我試圖訪問這個「myClass」對象,它使用PropertyPlaceholderConfigurer從外部環境變量中讀取並注入到「myClass」。任何指針?

更新:

我試圖用「RequestContextUtils提供的」的建議,但現在我得到「沒有找到WebApplicationContext的:不是在DispatcherServlet的請求」異常。 我嘗試訪問bean的JSP是應用程序的入口點。 我的視圖解析器是這樣的,

<bean id="viewResolver" 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix"> 
     <value>/WEB-INF/views/</value> 
    </property> 
    <property name="suffix"> 
     <value>.jsp</value> 
    </property> 
    <property name="exposedContextBeanNames"> 
     <value>myClass</value> 
    </property> 
    </bean> 

的JSP在嘗試訪問該「意見」的文件夾之外。請告知

+2

我不這樣做的Spring MVC,但不只是EL'$ {MyClass的}'可以在Spring MVC?無論如何,Java代碼不屬於JSP。 – BalusC

+1

你爲什麼試圖訪問JSP中的應用上下文?您正在使用MVC,視圖層的任何內容都應通過控制器公開。 –

+0

@BalusC:只有配置了視圖解析器才能將bean作爲屬性公開。 – axtavt

回答

4

WebApplicationContextUtils.getRequiredWebApplicationContext()返回與ContextLoaderListener(即applicationContext.xml)關聯的應用程序上下文。

爲了得到你需要調用RequestContextUtils.getWebApplicationContext(request)DispatcherServlet相關的情境。

或者,您可以配置InternalResourceViewResolver暴露豆作爲屬性。然後,您可以使用${myClass}訪問JSP中的bean。您可以通過將exposeContextBeansAsAttributes設置爲true(我認爲它會導致某些性能損失),或者顯式列出要使用exposedContextBeanNames公開的bean。

+0

根據此建議更新了我的問題。不幸的是,它不起作用在我的情況下 – Raghav

+1

@Srini:如果是這樣,你將無法訪問「DispatcherServlet」的上下文。爲了以防萬一,將所有JSP放在「DispatcherServlet」後面會更好。它也會解決你的問題。爲避免編寫微不足道的控制器,你可以使用'' – axtavt

+0

正如axtavt所建議的那樣,移動JSP以使其位於前端控制器的後面。感謝大家的建議 – Raghav

相關問題