Am trying to get the application context in my JSP page.
I have the following scriptlet in JSP.
WebApplicationContext appCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
MyClass myClass = (MyClass)(appCtx.getBean("myClass"));
When using this a null pointer exception is getting thrown for the application context.
What am I doing wrong here?
I dont have a application-context.xml file because I dont need one. I have the usual dispatcher-servlet.xml with handler mappings.
Also, as an added info:
I am trying to access this “myClass” object which is being injected using PropertyPlaceholderConfigurer which reads from external environmental variables and injects to “myClass”. Any pointers?
Update:
I tried using “RequestContextUtils” as suggested but now am getting “No WebApplicationContext found: not in a DispatcherServlet request” exception.
The JSP in which I am trying to access the bean is the entry point of the application .
My view resolver looks like this,
<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>
The JSP am trying to access is outside of this “views” folder. Please advise
WebApplicationContextUtils.getRequiredWebApplicationContext()returns an application context associated withContextLoaderListener(i.e.applicationContext.xml).To get a context associated with
DispatcherServletyou need to callRequestContextUtils.getWebApplicationContext(request).Alternatively, you can configure
InternalResourceViewResolverto expose beans as attributes. Then you can access beans in JSP as${myClass}. You can expose all beans by settingexposeContextBeansAsAttributestotrue(I think it incurs some performance penalty), or explicitly list beans to be exposed withexposedContextBeanNames.