标签

来源:互联网 发布:恺英网络股票行情 编辑:程序博客网 时间:2024/05/29 14:29

 

1、对数组进行循环遍历
使用<logic:iterate>标记可以用于遍历数组,以下是一段示例代码:

Java代码 复制代码
  1. <%   
  2. String[] testArray={"str1","str2","str3"};    
  3. pageContext.setAttribute("test",testArray);    
  4. %>   
  5. <logic:iterate id="show" name="test">    
  6. <bean:write name="show"/>    
  7. </logic:iterate>  

其结果为:
str1
str2
str3

另外,还可以通过length属性来指定输出元素的个数。如下面的代码:
Java代码 复制代码
  1. <logic:iterate id="show" name="test" length="2" offset="1">    
  2. <bean:write name="show"/>    
  3. </logic:iterate>  

offset属性指定了从第几个元素开始输出,如此处为1,则表示从第二个元素开始输出。
所以该代码的运行结果应当输出:
str2
str3

另外,该标记还有一个indexId属性,它指定一个变量存放当前集合中正被访问的元素的序号,如:
Java代码 复制代码
  1. <logic:iterate id="show" name="test" length="2" offset="1" indexId="number">    
  2. <bean:write name="number"/>:<bean:write name="show"/>    
  3. </logic:iterate>  
其显示结果为:
1:str2
2:str3



2、对HashMap进行循环遍历
Java代码 复制代码
  1. <%   
  2. HashMap countries=new HashMap();   
  3. countries.put("country1","中国");   
  4. countries.put("country2","美国");   
  5. countries.put("country3","英国");   
  6. countries.put("country4","法国");   
  7. countries.put("country5","德国");   
  8. pageContext.setAttribute("countries",countries);    
  9. %>   
  10. <logic:iterate id="country" name="countries">    
  11. <bean:write name="country" property="key"/>:   
  12. <bean:write name="country" property="value"/>    
  13. </logic:iterate>  

在bean:write中通过property的key和value分别获得HaspMap对象的键和值。其显示结果为:
country5:德国
country3:英国
country2:美国
country4:法国
country1:中国
由结果可看出,它并未按添加的顺序将其显示出来。这是因为HaspMap是无序存放的。



3、嵌套遍历
Java代码 复制代码
  1. <%   
  2. String[] colors={"red","green","blue"};   
  3. String[] countries1={"中国","美国","法国"};   
  4. String[] persons={"乔丹","布什","克林顿"};   
  5. ArrayList list2=new ArrayList();   
  6. list2.add(colors);   
  7. list2.add(countries1);   
  8. list2.add(persons);   
  9. pageContext.setAttribute("list2",list2);   
  10. %>   
  11. <logic:iterate id="first" name="list2" indexId="numberfirst">   
  12. <bean:write name="numberfirst"/>   
  13. <logic:iterate id="second" name="first">   
  14. <bean:write name="second"/>   
  15. </logic:iterate>   
  16. <br>   
  17. </logic:iterate>  


运行效果:
0 red green blue
1 中国 美国 法国
2 乔丹 布什 克林顿