Iterate over a List of Maps using s:iterator

前端 未结 1 1859
北海茫月
北海茫月 2021-02-03 13:09

I\'m trying to iterate through a List of Maps using s:iterator. I can iterate through the List without problems, but I can not get it to iterate through the entries of the map.

相关标签:
1条回答
  • 2021-02-03 13:26

    Here is a demo that loops through lists of map:

    import com.opensymphony.xwork2.ActionSupport;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    public class mapTest extends ActionSupport {
      public List<Map> listmap;
    
      public String execute(){
        listmap = new ArrayList();
        Map map = new HashMap();
        map.put("a", "alpha");
        map.put("b", "bravo");
        map.put("c", "charlie");
        listmap.add(map);
        Map map2 = new HashMap();
        map2.put("d", "delta");
        map2.put("e", "echo");
        map2.put("f", "foxtrot");
        listmap.add(map2);
        return SUCCESS;
      }
    }
    

    Here is the JSP to render it:

    <%@taglib prefix="s" uri="/struts-tags"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <body>
            <h1>Map Test</h1>
            <table>
                <thead>
                    <tr>
                        <th>List #</th>
                        <th>key</th>
                        <th>value</th>
                    </tr>
                </thead>
                <tbody>
                    <s:iterator value="listmap" status="stat">
                        <s:iterator>
                            <tr>
                                <th><s:property value="#stat.index"/></th>
                                <td><s:property value="key"/></td>
                                <td><s:property value="value"/></td>
                            </tr>
                        </s:iterator>
                    </s:iterator>
                </tbody>
            </table>
        </body>
    </html>
    

    Note the inner iterator is context sensitive it will use the last value pushed onto the stack. The status attribute gives us a IteratorStatus object each iteration which is useful if we want to know the current iteration.

    0 讨论(0)
提交回复
热议问题