Wolfgang
Wolfgang

Reputation: 2407

Access spring web application context beans in EL expression

I'm new to Spring MVC and have the following situation:

In WEB-INF/demoshop-servlet.xml I have the following line:

<bean id="someBean" class="com.xxx.xxx.web.SomeBean" />

I also have a JSP that contains a line like:

${someBean.someAttribute}

I expected that the attribute is read from the bean when the page is rendered but it's not. The expression is just ignored. (While other EL expressions with objects introduced in a ModelMap in the controller are evaluated correctly.)

In order to debug this a little I inserted the following to the JSP:

<% System.out.println(application.getAttribute("someBean")); %>

Which prints null.

What is missing, or what am I doing wrong here?

Upvotes: 2

Views: 3179

Answers (2)

Rajesh
Rajesh

Reputation: 796

Here have a method, you can get Spring bean in JSP file without Java code. Setup a Spring Web MVC XML file and add 1 property in viewResolver:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="exposeContextBeansAsAttributes" value="true"/>
</bean>

Now, You can get bean content in JSP like that:

<c:out value="${ bean.value }" />

Upvotes: 1

DwB
DwB

Reputation: 38300

Spring beans are not automatically made available to the JSP page, you have to put the bean in the appropriate scope (application, session, request, or page). You ave at least these options:

  1. Add the bean to the Model in your Controller
  2. Extend a View class and add the bean to the Model.

Upvotes: 1

Related Questions