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:
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.


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) {

// Initialise Java ServletRequest and Session Attributes
// from scope="request" or "session" and lazy-init="false" spring beans.
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext)
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());

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