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="">
  <beans:property name="attributes">
      <beans:entry key="MyBeautifulBean">
        <beans:ref bean="MyBeautifulBean" />
      [more beans here if needed]

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">
charles ross on April 06, 2019 at 19:35
This is a very nice article - but that is a POJO, and is not a Bean. A Bean should have getters and setters, default no-argument constructor.