How to access objects in EL expression language ${}

The expression ${foo} uses behind the scenes JspContext#findAttribute() which searches for attributes in PageContext, HttpServletRequest, HttpSession and ServletContext in this order by their getAttribute("foo") method whereby foo from ${foo} thus represents the attribute name "foo" and returns the first non-null object.

So, if you do in a servlet

ArrayList<Person> persons = getItSomehow();
request.setAttribute("persons", persons); // It's now available by ${persons}
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);

And call this servlet by URL, then you'll be able to iterate over it in page.jsp as follows:

<c:foreach items="${persons}" var="person">
    ${person.title}
<c:forEach>

The above is also equally valid when you put it in the session scope instead

request.getSession().setAttribute("persons", persons);

or even in the application scope

getServletContext().setAttribute("persons", persons);

EL will for title in ${person.title} implicitly look for a public instance (not static!) method prefixed with get in Person class like below:

public String getTitle() {
    return title;
}

The field title does not necessarily need to exist in the class (so you can even return a hardcoded string and keep using ${person.title}), and it does not necessarily need to be an instance field (so it can also be a static field, as long as the getter method itself isn't static).

Only boolean (not Boolean!) getters have a special treatment; EL will implicitly look for a public method prefixed with is. E.g. for a ${person.awesome}:

public boolean isAwesome() {
    return awesome;
}

See also:

  • Our EL wiki page
  • How do servlets work? Instantiation, sessions, shared variables and multithreading
  • How to avoid Java code in JSP files?
  • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
  • Use EL ${XY} directly in scriptlet <% XY %>
  • How does Java expression language resolve boolean attributes? (in JSF 1.2)

<c:forEach var="item" items="${names}"> ${item.title}  </c:forEach>

names should be in the set as attribute available for the view