Struts logic:iterate标签的总结

来源:互联网 发布:http js.shxedc.com 编辑:程序博客网 时间:2024/05/01 13:32

<logic:iterate> 是Logic 标签库中最复杂的标签,也是用途最广的一个标签,它能够在一个循环中遍历数组、Collection、Enumeration、Iterator 或 Map 中的所有元素。 
1. 遍历集合 
<logic:iterate> 的 name 属性指定需要进行遍历的集合对象, 它每次从集合中检索出一个元素, 然后把它放在page 范围内, 并以id 属性指定的字符串来命名这个元素, 例如: 

<% 
  Vector animals = new Vector(); 
  animals.addElement("Dog"); 
  animals.addElement("Cat"); 
  animals.addElement("Bird"); 
  animals.addElement("Chick"); 
  request.setAttribute("Animals", animals); 
%> 
<logic:iterate id="element" name="Animals"> 
  <bean:write name="element"/><br> 
</logic:iterate> 
以上代码先定义了一个Vector 类型的集合变量 Animals, 它存放在request 范围内. 接下来<logic:iterate> 标签在一个循环中遍历Animals 集合(这个集合名就是在标签中的name 属性的值)中所有元素, 每次检索到一个元素, 就把它命名为"element"(标签id 属性的值), 并存放在page 范围内. 
在<logic:iterate> 中, 还嵌套了一个<bean:write>标签, 它用于输出每个元素的内容. 以上代码的输出内容如下: 
Dog 
Cat 
Bird 
Chick 

length   属性指定需要遍历的元素的数目, 如果没有设置length 属性, 就遍历集合中的所有元素. 
offset   属性指定开始遍历的起始位置, 默认值为 "0" , 表示从集合的第一个元素开始遍历. 
indexId 属性定义一个代表当前遍历元素序号的变量, 这个变量被存放在 page 范围内, 可以被标签主体的<bean:write> 标签访问. 例如: 
<logic:iterate 
    id="element"     // 指定输出元素的名 与 <bean:write> 中name 属性一致 
    indexId="index"   // 遍历元素序号的变量, 这个变量放在page 范围内 
    name="Animals"   // request 中的集合名, 从中取循环取出元素 
    offset="1"       // 从集合的第 2 条记录开始取数 
    length="2">       // 取出 2 个元素 
  <bean:write name="index"/>.       // 输出每个元素的序号, 与indexId 的属性一致 
  <bean:write name="element"/><br> // 输出每个元素的内容, 与id 的属性一致 
</logic:iterate> 
2. 遍历Map 
<logic:iterate> 标签还可以遍历HashMap 中的元素, 例如: 
<% 
  HashMap months = new HashMap(); 
  
  months.put("Jan","January"); 
  months.put("Feb","February"); 
  months.put("Mar","March"); 
  
  request.setAttribute("month", months); 
%> 
<logic:iterate id="element" indexId="ind" name="months"> 
  <bean:write name="ind"/>.                   // 序号 
  <bean:write name="element" property="key"/>:   // 键名 
  <bean:write name="element" property="value"/>   // 键值 
</logic:iterate> 
以上代码先定义一个名为"months" 的HashMap, 存放在request 范围内. 接下来在<logic:iterate> 标签遍历months 对象的每一个元素, 每一个元素包含一对 key/value . 在<logic:iterate> 标签主体中包含三个<bean:write> 标签, 分别输出每个元素的序号、key 和 value. 以上代码的输出内容如下: 
0.Mar: March 
1.Feb: February 
2.Jan: January 
如果HashMap 中的每个元素的 value 是集合对象, 则可以采用嵌套的<logic:iterate>标签遍历集合中的所有对象, 例如: 
<% 
    HashMap h = new HashMap(); 
    String vegetables[] = {"pepper","cucumber"}; 
    String fruits[] = {"apple","orange","banana","cherry","watermelon"}; 
    String flowers[] = {"chrysanthemum","rose"}; 
    String trees[] = {"willow"}; 
    
    h.put("Vegetables", vegetables); 
    h.put("Fruits",fruits); 
    h.put("Flowers",flowers); 
    h.put("Trees",trees); 
    
    request.setAttribute("catalog",h); 
%> 
<logic:iterate   id="element"       // 与<bean:write> 中的name 属性对应, 输出内容 
            indexId="ind"       // 与<bean:write> 中的name 属性对应, 输出序号 
            name="catelog">   // 指定输出元素的名称 
  <bean:write name="ind"/>.     // 输出序号 
  <bean:write name="element"   // 与<logic:iterate>中id 属性对应 
property="key"/>   // 集合中的键名 
  <logic:iterate 
      id="elementValue"   // 与<bean:write> 中的name 属性对应 
      name="element"   // 指定输出元素的名称 
      property="value"   // 集合中的键值 
      length="3"         // 取3 个元素 
offset="1">             // 从第 2 个位置取 
-------<bean:write name="elementValue"/> 
</logic:iterate> 
</logic:iterate> 

以上代码先定义一个名为"catelog" 的HashMap , 存放在request 范围内, 它的每个元素的value 为字符串数组. 
接下来外层的<logic:iterate>标签遍历HashMap 中的所有元素, 内层的<logic:iterate>标签访问每个元素的value 属性, 遍历value 属性引用的字符串数组中的所有元素. 
3. 设置被遍历的变量 
可以通过以下方式来设置需要遍历的变量 
(1) 设置name 属性, name 属性指定需要遍历的集合或Map, 例如: 
  <logic:iterate id="element" name="Animals"> 
    <bean:write name="element"/> 
  </logic:iterate> 
(2) 设置name 属性和property 属性, name 属性指定一个JavaBean, property 属性指定JavaBean 的一个属性, 这个属性为需要遍历的集合或Map, 例如: 
  <logic:iterate id="element" indexId="ind" name="catelog"> 
    <bean:write name="ind"/> 
    <bean:write name="element" property="key"/> 
    <logic:iterate id="elementValue" name="element" property="value" length="3" offset="1"> 
      --------<bean:write name="elementValue"/> 
    </logic:iterate> 
  </logic:iterate> 
(3) 设置collection 属性, collection 属性指定一个运行时表达式, 表达式的运算结果为需要遍历的集合或Map, 例如: 
  
  <logic:iterate id="header" collection"<%=request.getHeaderNames()%>"> 
    <bean:write name="header"/> 
  </logic:iterate> 
4. 读取JavaBean 中的数据 
(1) 在Jsp 页面中加入JavaBean 如: 
  <jsp:useBean id="articleClasses" class="com.GetArticleClasses"/> 
  上面这个JavaBean 要求必须存在一个集合数组对象,如Vector,Collection,ArrayList 等;在这个JavaBean 的构造函数中,取得数据 
库中的数据,并将其存入数组对象中。 
(2) 使用<logic:iterate> 标签,取出JavaBean 中存放的数组对象中的数据 
  <logic:iterate 
        id="aClasses"         // id   : 给检索出的元素所命的名. 
        name="articleClasses"   // name : JavaBean 在页面中所设置的引用ID. 
        property="coll">       // coll : JavaBean 中的集合数组属性名称. 
    <tr> 
      <td onMouseOver="this.bgColor='#FFFFFF'" onMouseOut="this.bgColor=''">   
    <html:link page="/articleListAction.do" 
              paramId="classId" 
              paramName="aClasses" 
              paramProperty="classId"> 
    <bean:write name="aClasses"   // 与<logic:iterate> 标签中的id 属性相对应 
        property="className" />   // 取出JavaBean中, 存放在集合对象中的,对象的className 属性值 
    </html:link> 
    </td> 
    </tr> 
  </logic:iterate> 
(3) 在JavaBean 中的集合对象中存放实体对象的语句如下: 
  ...... 
  public class GetArticleClasses 
  { 
    // 数据集合 
    private Collection coll; 

    // 返回数据集合 
    public Collection getColl() 
    { 
      return coll; 
    } 
    // 构造函数, 取出数据,存入集合中 
    public GetArticleClasses() 
    { 
      coll = new ArrayList(); 
      try{ 
        // 数据库连接 
        Connection connection = DBConnection.getConnection(); 
        if(connection != null) 
        { 
          Statement statement = connection.createStatement(); 
          ResultSet resultset; 
          ArticleClass articleclass; 
          resultset = statement.executeQuery("SELECT * FROM table ORDER BY id"); 
          while( resultset.next()) 
          { 
            articleclass = new ArticleClass(); 
            articleclass.setId(resultset.getInt("id")); 
            articleclass.setClassId(resultset.getString("class")); 
            articleclass.setClassName(resultset.getString("name")); 
            
            coll.add(articleclass)) 
      } 
      resultset.close(); 
      connection.close(); 
    } else { 
      coll = null; 
    } 
  } catch(Exception exception) { 
    coll = null; 
  } 

 

Iterate主要用来处理在页面上输出集合类,集合一般来说是下列之一: 
1、 java对象的数组 
2、 ArrayList、Vector、HashMap等 
具体用法请参考struts文档,这里不作详细介绍 

现在定义一个class,User.java 把它编译成User.class 

package example; 
import java.io.Serializable; 
public final class User implements Serializable { 
private String name = null; 
private String password = null; 

public String getName () { 
return (this.name); 


public void setName(String name) { 
this.name = name; 


public String getPassword () { 
return (this. password); 


public void setPassword (String password) { 
this. password = password; 




然后在一个struts webapplication中创建一个jsp,例如iterate.jsp 

<%@ page language="java" %> 
<%@ page import="example.*"%> 
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 

<% 
java.util.ArrayList list = new java.util.ArrayList(); 
User usera=new User(); 
usera.setName("white"); 
usera.setPassword("abcd"); 
list.add(usera); 
User userb=new User(); 
userb.setName("mary"); 
userb.setPassword("hijk"); 
list.add(userb); 
session.setAttribute("list", list); 
%> 
<html><body><table width="100%"> 
<logic:iterate id="a" name="list" type=" example.User "> 
<tr><td width="50%"> 
name: <bean:write name="a" property="name"/> 
<td/><td width="50%"> 
password: <bean:write name="a" property="password"/> 
</td></tr> 
</logic:iterate> 
</table></body></html> 
将User.class, iterate.jsp放到相应的目录,运行iterate.jsp你就可以看到iterate的效果了 

iterate标记 
id 脚本变量的名称,它保存着集合中当前元素的句柄。 
name 代表了你需要叠代的集合,来自session或者request的属性。 
type 是其中的集合类元素的类型 

bean的write标记是用来将属性输出的,name用来匹配iterate的id,property用来匹配相应类的属性<logic:iterate>用法详解22007-04-04 20:34<login:iterate>标记用于在页面中创建一个循环,以此来遍历如数组、Collection、Map这样的对象。该标记的功能强大,在Struts应用的页面中经常使用到。
1、对数组进行循环遍历
  使用<logic:iterate>标记可以用于遍历数组,以下是一段示例代码:
 程序代码<%
String[] testArray={"str1","str2","str3"}; 
pageContext.setAttribute("test",testArray); 
%>
<logic:iterate id="show" name="test"> 
<bean:write name="show"/> 
</logic:iterate>
  在上面的代码中,首先定义了一个字符串数组,并为其初始化。接着,将该数组存入pageContext对象中,命名为test1。然后使用<logic:iterate>标记的name属性指定了该数组,并使用id来引用它,同时使用<bean:write>标记来将其显示出来。其结果为:
str1 
str2 
str3 

  另外,还可以通过length属性来指定输出元素的个数。如下面的代码:
 程序代码<logic:iterate id="show" name="test" length="2" offset="1"> 
<bean:write name="show"/> 
</logic:iterate>
  其中length属性指定了输出元素的个数,offset属性指定了从第几个元素开始输出,如此处为1,则表示从第二个元素开始输出。所以该代码的运行结果应当输出:
str2
str3

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

2、对HashMap进行循环遍历
 程序代码<%
HashMap countries=new HashMap();
countries.put("country1","中国");
countries.put("country2","美国");
countries.put("country3","英国");
countries.put("country4","法国");
countries.put("country5","德国");
pageContext.setAttribute("countries",countries); 
%>
<logic:iterate id="country" name="countries"> 
<bean:write name="country" property="key"/>:
<bean:write name="country" property="value"/> 
</logic:iterate>
  在bean:write中通过property的key和value分别获得HaspMap对象的键和值。其显示结果为:
country5:德国 
country3:英国 
country2:美国 
country4:法国 
country1:中国 
  由结果可看出,它并未按添加的顺序将其显示出来。这是因为HaspMap是无序存放的。

3、嵌套遍历
 程序代码<%
String[] colors={"red","green","blue"};
String[] countries1={"中国","美国","法国"};
String[] persons={"乔丹","布什","克林顿"};
ArrayList list2=new ArrayList();
list2.add(colors);
list2.add(countries1);
list2.add(persons);
pageContext.setAttribute("list2",list2);
%>
<logic:iterate id="first" name="list2" indexId="numberfirst">
<bean:write name="numberfirst"/>
<logic:iterate id="second" name="first">
<bean:write name="second"/>
</logic:iterate>
<br>
</logic:iterate>
  运行效果:
0 red green blue 
 

原创粉丝点击