第3.3式. 顯示索引屬性
問題
在一個JSP 頁面中,你需要訪問一個對象中的索引的屬性。
動作要領
使用bean.property[index]來訪問索引的值,如Example 3-1所示。
Example 3-1. 訪問索引屬性
<@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 也支持對索引屬性的訪問,如Example 3-2 所示。
Example 3-2. 訪問索引屬性(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>

動作變化
索引的屬性是Struts標簽中最容易誤解的一個部分。一個索引屬性是表達一組值的JavaBean 屬性,而不是一個單獨的標量值。索引屬性通過下面格式的getter 方法進行訪問:

public Foo getSomeProperty (int index)
{
}
同時,索引屬性則通過下面格式的setter 方法進行設置:

public void setFoo(int index, Foo someProperty)
{
}
我們來考慮一個表示日歷的JavaBean。CalendarHolder類的代碼如Example 3-3 所示,它有一個名為monthSet的嵌套屬性,表達日歷中的月份。
Example 3-3. Calendar JavaBean
package com.oreilly.strutsckbk;


public class CalendarHolder
{
private MonthSet monthSet;


public CalendarHolder( )
{
monthSet = new MonthSet( );
}

public MonthSet getMonthSet( )
{
return monthSet;
}
}

MonthSet類的代碼則如Example 3-4 所示,它是一個具有索引屬性的類,該屬性表達月份的名稱("January," "February," 等等)。
Example 3-4. 具有索引屬性的類
package com.oreilly.strutsckbk;


public class MonthSet
{

static String[] months = new String[]
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};

public String[] getMonths( )
{
return months;
}


public String getMonth(int index)
{
return months[index];
}

public void setMonth(int index, String value)
{
months[index] = value;
}
}

我們的目標是訪問在JSP頁面中訪問CalendarHolder實例的monthSet屬性的索引屬性month,代碼片斷如下所示:
<jsp:useBean id="calendar" class="com.oreilly.strutsckbk.CalendarHolder"/>

<ul>
<li><bean:write name="calendar" property="monthSet.months[0]"/></li>
<li><bean:write name="calendar" property="monthSet.months[1]"/></li>
<li><bean:write name="calendar" property="monthSet.months[2]"/></li>
</ul>

如果顯示的索引屬性要動態才能決定它是什么,那么使用的索引要使用JSP 腳本變量來進行設置。你可以使用scriptlet 來產生屬性值,如下所示:
You have selected month number <bean:write name="monthIndex"/>:
<bean:write name="calendar"
property='<%= "monthSet.month[" + monthIndex + "]" %>'

但是使用scriptlet 會導致極端難以閱讀和維護的JSP 頁面。如果使用JSTL,事情會變得更清爽一些:
You have selected month number <c:out value="${monthIndex}"/>:
<c:out value="${calendar.monthSet.month[monthIndex]}"/>

通常,索引屬性是在一個循環內動態訪問的。假設你想要使用Struts logic:iterate標簽顯示月份的列表。這個標簽將在整個Collection 或者數組之上進行迭代。下面是你可以如何以一個排序列表顯示所有月份的例子:
<ol>
<logic:iterate id="monthName" name="calendar" property="monthSet.months">
<li><bean:write name="monthName"/></li>
</logic:iterate>
</ol>

重申一下, JSTL 也是一個替代選擇。JSTL c:forEach標簽將比Struts logic:iterate標簽要容易使用一些。下面是如何使用JSTL來產生上面的同一個排序列表的代碼:
<ol>
<c:forEach var="monthName" items="${calendar.monthSet.months}">
<li><c:out name="${monthName}"/></li>
</c:forEach>
</ol>

相關動作
第3.4式在JSTL循環中使用索引屬性。
第3.5式則提供了一個更加詳細的關于在JSTL循環中使用索引屬性的說明。