JSP use Expression Language to Access Spring Bean

JSP use Expression Language to Access Spring Bean

In Spring bean you can easily access other bean. There have a 3 method to get bean in Java class.

Java Annotation:

private MyBean bean;


<bean id="person" class="org.springframework.beans.TestBean" scope="prototype">
    <property name="age" value="10"/>
    <property name="spouse">
        <bean class="org.springframework.beans.TestBean">
            <property name="age" value="11"/>

or get bean in run time:

ApplicationContext context =  WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object bean = context.getBean("myBean");

In JSP, You can use the third method to get Spring bean, but I don’t like add Java code into JSP file.

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"/>

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

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

Spring will auto inject all bean into JSP file.