How to configure in my spring project to retrieve the applicationContext object in jsp using JSTL.
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(application);
%>
application
is the JSP defined ServletContext.
If you want to retrieve a bean and use JSTL, you can then do something like:
<%pageContext.setAttribute("bean", context.getBean("myBean"));%>
<c:out value="${bean.property}"/>
But, just because you can, doesn't mean you should. If you are doing anything more than displaying a bean's property you probably want to put this in a Servlet or some other controller.
Also, you do not want to be using the ApplicationContext as a way to pass beans between your controllers and views.
Spring root web application context is available in servlet context attribute named: org.springframework.web.context.WebApplicationContext.ROOT
:
${applicationScope['org.springframework.web.context.WebApplicationContext.ROOT']}
Haven't tried it, but should be accessible via JSTL. But what you want to achieve? Is JSP really a good place to fetch beans manually and perform some business operations? Shouldn't you do all the work in servlet/controller and let JSP do only the view, as it was intended?
EDIT: I was worng, it doesn't work. Anyway, you would be able to access all beans by name, with no need of ApplicationContext, depending on what you need to do.
.
If you set property exposeContextBeansAsAttributes of InternalResourceViewResolver to true, you would be able to access from JSP using EL: ${applicationContext}. Depending of what you're trying to do, this can be more or less suitable.
EDIT: Your view resolver for JSP must be something similar to:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="exposeContextBeansAsAttributes" value="true" />
</bean>
The best thing is that you can get the bean you want by its name. So, probably, you won't need ApplicationContext there.
For Spring 4 it works well:
<%
ApplicationContext context = RequestContextUtils.findWebApplicationContext(request);
%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With