logic:iterate
logic:iterate标签用来迭代集合,您可以使用如下方式来为这个标签指定其要叠代的集合:
使用一个运行时表达式,这个表达式的值是一个集合。
用name属性引用一个JSP Bean,这个JSP Bean本身就是一个集合(或者干脆直接引用集合类.)。
用name属性引用一个JSP Bean,这个JSP Bean的一个属性是一个集合,这时可以联合使用property来指定这个集合。
上面所提到的集合可以是:
对象类型或原子类型的数组(Array)。
java.util.Collection的实现,包括ArrayList,Vector。
java.util.Enumeration的实现。
java.util.Iterator的实现。
java.util.Map的实现,包括HashMap,Hashtable和TreeMap。
如果您叠代的集合中含有null的值,这时需要采取一定的措施,因为这时logic:iterate不会在page作用域中创建对象。一般是使用<logic:present>标签或<logic:notPresent>标签来判断一下。
iterate标签的常用属性如下:
●    id:指定页面范围的jsp变量的名称,该变量存储每次迭代的当前集合元素的引用.也就是说,id属性的值时可以任意写的,他存储了迭代当前集合元素的值.不过要保证<bean:write>标签的 name属性的值和iterate标签的id值一致.如下图三所示.
●    name:指定包含要迭代的集合对象的名称,如果还指定了property属性,将调用对象中该属性定义的一个字段的值获取方法,以返回一个要迭代的集合.也就是说,在没有property属性的时候,name属性指的是一个集合,而在有property属性的时候,name属性指的一般是一个form-bean,当然你也可以用jsp:userBean标签指定一个bean,而property属性指的是这个form-bean(bean)的一个集合类.
 
下面是logic:iterate叠代ArrayList的示例的对象引用关系和部分代码:
图示 3. logic:iterate中对象的引用关系
 

图中的persons列表是在ListAction中填充的,在这里只是简单的加入了三个Person对象,在实际的应用中这些数据应该取自数据库。具体的代码如下:
public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request,        HttpServletResponse response) {
 
  ListForm listForm = (ListForm) form;
       
  List<Person> persons = new ArrayList<Person>();
       
  Person person1 = new Person();
  person1.setId("00001");
  person1.setName("赵辰");
       
  Person person2 = new Person();
  person2.setId("00002");
  person2.setName("李为芳");
       
  Person person3 = new Person();
  person3.setId("00003");
  person3.setName("王微");
       
  persons.add(person1);
  persons.add(person2);
  persons.add(person3);
       
  listForm.setPersons(persons);
       
  return mapping.findForward("success");
}
标签输出的结果为:
00001-->赵辰
00002-->李为芳
00003-->王微
 
 
 
在struts中,读取数据库中的多条数据然后显示到jsp页面上可以用如下的方法去做:
1.在Form中定义一个ArrayList import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class AlloperationForm extends ActionForm {
private ArrayList list;
public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { }
public void reset(ActionMapping mapping, HttpServletRequest request) {} public ArrayList getList() { return list; } public void setList(ArrayList list) { this.list = list; }}
2.在Action中调用一个返回游标的存储过程,得到所有的记录,找把它封装成一个Bean. public class AlloperationAction extends Action {public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AlloperationForm operationForm =(AlloperationForm)form;
Connection conn=ConnectDataBase.connection();
String callFunction="{?=call alloperation.getalloperation}";
ResultSet rs = null;
ArrayList alist=new ArrayList(); try { CallableStatement stmt=conn.prepareCall(callFunction);
stmt.registerOutParameter(1,OracleTypes.CURSOR);
stmt.execute();
rs = ((OracleCallableStatement)stmt).getCursor(1);
while(rs.next())
{
String operationName=rs.getString(1);
String operationType=rs.getString(2);
String charge=rs.getString(3);
String charegeType=rs.getString(4);
System.out.println("operationName"+operationName);
System.out.println("operationType"+operationType);
System.out.println("charge"+charge);
System.out.println("chargeType"+charegeType);
AllOperationBean operationBean=new AllOperationBean
(operationName,operationType,charge,charegeType);
alist.add(operationBean);
}
conn.close();
operationForm.setList(alist);
} catch (SQLException e) { e.printStackTrace();
}
return mapping.getInputForward();
}
}
定义的bean: package com.penguin.bean;
public class AllOperationBean {
private String operationName;
private String operationType;
private String chargeType;
private String charge;
public AllOperationBean(String operationName,String operationType,String charge,String chargeType)
{ this.operationName=operationName;
this.operationType=operationType;
this.charge=charge;
this.chargeType=chargeType;
} public String getCharge() {
}
public void setCharge(String charge) {
this.charge = charge;
}
public String getChargeType() {
return chargeType;
}
public void setChargeType(String chargeType) {
this.chargeType = chargeType;
}
public String getOperationName() {
return operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
} public String getOperationType() {
return operationType;
} public void setOperationType(String operationType) {
this.operationType = operationType;
}
}
在jsp页面中用标签调用代码如下图:其中alloperationFormation是在struts配置文件中定义的form-bean的名称.
        

 
通过上述步骤就可以在jsp页面中显示出多条记录了..
 
 
 
<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" , 表示从集合的第一个元素开始遍历.
scope:可以指定指定作用范围如:scope=”request”或session.
    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=''''">&nbsp;&nbsp;&nbsp;&nbsp;
             <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;
        }
    }
}