1. 程式人生 > >struts2中iterator標籤的相關使用

struts2中iterator標籤的相關使用

在說明s:iterator標籤的使用前,先了解下struts2中的Value Stack。這裡參考了webwork中對Value Stack的描述,由於struts2是在webwork的基礎上進行升級的,因此webwork對於Value Stack的表述同樣適用於struts2。在這裡不描述Value Stack具體做什麼,但有兩點需要注意:

  1.  一個value stack本質上是一個List;
  2. 在棧中呼叫[n]將返回一個從位置n開始的子棧;

對於2舉個例子說明。假定Value Stack包含了[model,action,others],那麼

  1. [0] --- 返回 [model,action,others];
  2. [1] --- 返回 [action,others];
  3. [2] --- 返回 [others];

現在將開始介紹s:iterator的一些使用。以下程式碼片段均在開發環境eclipse3.4 wtp、tomcat5.5、jdk5上使用struts2.1.6測試通過。

1)、訪問 days

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

2)、使用top 關鍵字使用(過濾掉Monday)

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

  • top 指代當前迭代元素,可以為物件;
  • 這裡的top可用[0].top替代,但不能使用[0]。[0]代表整個棧物件。如果單純呼叫[0]將會呼叫其toString()方法輸出物件資訊;

3)、使用 last / first關鍵字

defined  String[][] aTs = { { "一", "二", "三", "四" },{ "一一", "二二", "三三", "四四"} };

 

  • iterator 標籤中的status屬性代表當前迭代的位置;
  • #of.last用於判斷當前迭代到的元素是否為最後一個元素;
  • last返回一個boolean型別;
  • first返回一個boolean型別;

4)、使用 odd/ even關鍵字

下面的例子要實現每行輸出顏色不同的效果。

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

  • odd關鍵字用來判斷當前迭代位置是否為奇數行。odd返回boolean型別;
  • even關鍵字用來判斷當前迭代位置是否為偶數行。even返回boolean型別

5)、總結下,當宣告iterator的status屬性時,通過#statusName.method可以使用以下方法:

  • even : boolean - 如果當前迭代位置是偶數返回true
  • odd : boolean - 如果當前迭代位置是奇數返回true
  • count : int - 返回當前迭代位置的計數(從1開始)
  • index : int - 返回當前迭代位置的編號(從0開始)
  • first : boolean - 如果當前迭代位置是第一位時返回true
  • last : boolean - 如果當前迭代位置是最後一位時返回true
  • modulus(operand : int) : int - 返回當前計數(從1開始)與指定運算元的模數

6)、最後再來看下在iterator中呼叫value stack的用法。

假定countries是一個List物件,每一個country有一個name屬性和一個citys List物件,並且每一個city也有一個name屬性。那麼我們想要在迭代citys時訪問所屬country的name屬性就的用如下方式:

  • 這裡的 <ww:property value="name"/>取的是ctiy.name;<ww:property value="[1].name"/>取得是country.name
  • <ww:property value="[1].name"/> 等價於 <ww:property value="[1].top.name"/>
  • we refer to a specific position on the stack: '[1]'. The top of the stack, position 0, contains the current city, pushed on by the inner iterator; position 1 contains the current country, pushed there by the outer iterator.(city處於當前棧,即top或者[0],而[1]指明瞭外層iterator物件,即country)
  •  '[n]'標記引用開始位置為n的子棧(sub-stack),而不僅僅是位置n處的物件。因此'[0]'代表整個棧,而'[1]'是除top物件外所有的棧元素。