Aug 24, 2010

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:
@Autowired
private MyBean bean;


XML:
<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"/>
        </bean>
    </property>
</bean>

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

Now, You can get bean content in JSP like that:
<c:out value="${ bean.value }" />

Spring will auto inject all bean into JSP file.


2 comments:

avg said...

we gon' party tonight

akme said...

You can provide your own RequestContextListener extends org.springframework.web.context.request.RequestContextListener {

public void requestInitialized(ServletRequestEvent requestEvent) {
super.requestInitialized(requestEvent);

// Initialise Java ServletRequest and Session Attributes
// from scope="request" or "session" and lazy-init="false" spring beans.
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext)
WebApplicationContextUtils.getRequiredWebApplicationContext(requestEvent.getServletContext());
ConfigurableListableBeanFactory cbf = (ConfigurableListableBeanFactory) ctx.getBeanFactory();
for (String name : cbf.getBeanDefinitionNames()) {
BeanDefinition defn = cbf.getBeanDefinition(name);
if ((WebApplicationContext.SCOPE_REQUEST.equals(defn.getScope())
|| WebApplicationContext.SCOPE_SESSION.equals(defn.getScope()) ) && !defn.isLazyInit()) {
//out.println(""+ name +" "+ defn.getScope());
cbf.getBean(name);
}
}
}

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code