3.3. Displaying Indexed Properties

Problem

On a JSP page, you need to access data from an indexed property of an object.

Solution

Use bean.property[ index ] to access the indexed value, as shown in Example 3-1.

Example 3-1. Accessing indexed properties

<@taglib uri=http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>

<ul>
  <li><bean:write name="foo" property="bar.baz[0]"/></li>
  <li><bean:write name="foo" property="bar.baz[1]"/></li>
  <li><bean:write name="foo" property="bar.baz[2]"/></li>
</ul>

JSTL supports access to indexed properties, as shown in Example 3-2.

Example 3-2. Accessing indexed properties (JSTL)

<@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<ul>
  <li><c:out value="${foo.bar.baz[0]}"/></li>
  <li><c:out value="${foo.bar.baz[1]}"/></li>
  <li><c:out value="${foo.bar.baz[1]}"/></li>
</ul>

Discussion

Indexed properties are one of the most misunderstood aspects of the Struts tags. An indexed property is a JavaBean property that represents a set of values, not a single scalar value. Indexed properties are accessed using a getter method of the following form:

public Foo getSomeProperty (int index) { ... }

Likewise, indexed properties are set using a setter method of this form:

public void setFoo(int index, Foo someProperty) { ... }

Consider a JavaBean representing a calendar. The CalendarHolder class shown in Example 3-3 has a nested property representing the months in a calendar named monthSet.

Example 3-3. Calendar JavaBean

package com.oreilly.strutsckbk; public class CalendarHolder ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.