Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a List of Maps using s:iterator

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. So far I've got this:

[..]
<s:iterator value="records" status="recordsStatus" var="record">
        <s:if test="#recordsStatus.index ==0">
            <tr>
                <td colspan="*"></td>
            </tr>
        </s:if>
        <tr>
            <s:iterator value="record.entrySet()" status="fieldStatus">
            <td>
                <s:property value="key"/>/<s:property value="value"/>
            </td>
            </s:iterator>
        </tr>
    </s:iterator>
[..]

The tag generates the

<tr></tr>

for each entry, but it is not going throug the second iterator, so I suppose I'm doing something wrong with the value attribute. Can you help me with it?

Thanks

Jose

like image 609
Jose L Martinez-Avial Avatar asked Dec 13 '10 20:12

Jose L Martinez-Avial


1 Answers

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.

like image 108
Quaternion Avatar answered Sep 30 '22 16:09

Quaternion