Like it!

Join me on Facebook!

Like it!

How to expose Java beans to a JSP page in Spring MVC

ServletContextAttributeExporter definitely saved my life.

Recently I needed to expose a Java bean to a JSP page through Spring MVC framework, version 4.x. After a bit of struggle, I finally managed to do it with no blood loss.

Say you have a simple bean that contains a list of stuff:

public class MyBeautifulBean
{
  public List<String> values;
}

And you want to print that stuff in your JSP pages. To do that we have to rely on the so-called ServletContextAttributeExporter, an exporter utility that takes Spring-defined objects and exposes them as ServletContext attributes. That's exactly what I want! First of all open your Spring configuration file and add what follows wherever you like:

<beans:bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
  <beans:property name="attributes">
    <beans:map>
      <beans:entry key="MyBeautifulBean">
        <beans:ref bean="MyBeautifulBean" />
      </beans:entry>
      [more beans here if needed]
    </beans:map>
  </beans:property>
</beans:bean>

Then in any JSP page just print the content as you would do with a regular variable. In my example I iterate over a list of String's:

<c:forEach items="${MyBeautifulBean.values}" var="value">
  ${value}
</c:forEach>
comments