Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

applicationContext object in JSP

Tags:

spring

How to configure in my spring project to retrieve the applicationContext object in jsp using JSTL.

like image 437
rajputhch Avatar asked Mar 01 '11 12:03

rajputhch


4 Answers

<%@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.

like image 158
AngerClown Avatar answered Oct 11 '22 21:10

AngerClown


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?

like image 44
Tomasz Nurkiewicz Avatar answered Oct 11 '22 22:10

Tomasz Nurkiewicz


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.

like image 26
sinuhepop Avatar answered Oct 11 '22 22:10

sinuhepop


For Spring 4 it works well:

<%
ApplicationContext context = RequestContextUtils.findWebApplicationContext(request);
%>
like image 22
Pavel Vlasov Avatar answered Oct 11 '22 20:10

Pavel Vlasov