我試圖在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在嘗試訪問該「意見」的文件夾之外。請告知
我不這樣做的Spring MVC,但不只是EL'$ {MyClass的}'可以在Spring MVC?無論如何,Java代碼不屬於JSP。 – BalusC
你爲什麼試圖訪問JSP中的應用上下文?您正在使用MVC,視圖層的任何內容都應通過控制器公開。 –
@BalusC:只有配置了視圖解析器才能將bean作爲屬性公開。 – axtavt