• struts标签<logic:iterate>的用法


    <logic: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> 

    -----------

    假设List<T> ts已经保存了一个结果集,并且已经request.setAttribute("ts",ts)

    在JSP页面中

    <logic:iterate id="t" name="ts" type="com.feng.T">

        <bean:write name="t" property="t某个属性" />

    </logic:write>

    logic:iterate 中的 name 代表需要遍历的集合,来自session或request;id保存几何元素中当前的元素(名字可以自己起);type 指定集合中元素的类型那个,即类T的全路径,在此假设是com.fengdi.T

    bean:write 中的 name匹配logic:iterate中的id;property 匹配相应的元素属性

    -----------

    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中对象的引用关系

    关于struts中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;
            }
        }
    }

  • 相关阅读:
    小小的学习FPGA建议
    不厌其烦的四大集成电路
    关于FPGA复位的认识
    FPGA与图像处理
    谈谈对zynq的浅显理解
    嵌入ARM硬核的FPGA
    FPGA时序约束一点总结
    FPGA时序优化简单窍门
    学习FPGA,踏上一步台阶
    使用poi读取word2007(.docx)中的复杂表格
  • 原文地址:https://www.cnblogs.com/qq3245792286/p/6270530.html
Copyright © 2020-2023  润新知