Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

jsp - How to iterate over a nested map in <c:forEach>

I've a Map in a bean as follows:

public class TaskListData {
    private Map<String, String[]> srcMasks = new HashMap<String, String[]>();
    private Map<Integer, Map<String, String[]>> ftqSet = new HashMap<Integer, Map<String, String[]>>();

    public void setFTQSet(Integer ftqid, String[] src, String[] masks) {  
        srcMasks.put("srcDir", src);
        srcMasks.put("masks", masks);
        ftqSet.put(ftqid, srcMasks);
    }

This ftqSet fits in below datastructure:

feedId = "5",
feedName = "myFeedName",
ftqSet => {
            1 => {
                    srcDirs = ["/path/string"],
                    masks = ["p.txt", "q.csv"]
                 }
            2 => { ...
                 }
          }, ...

In my test JSP file I've been trying to access the data using <c:forEach>:

<c:forEach items="#{bean.ftqSet}" var="f">
    this text does not print
    ${f.feedId}
</c:forEach>

But it's not outputting ${f.feedId}. Why would this be? How would I access this structure's individual elements so I can create a nice table?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Each iteration of Map in a c:forEach gives a Map.Entry instance which in turn has getKey() and getValue() methods. It's similar to doing for (Entry entry : map.entrySet()) in plain Java.

E.g.

<c:forEach items="#{bean.map}" var="entry">
    <h:outputText value="Key: #{entry.key}, Value: #{entry.value}" /><br />
</c:forEach>

In case of a Map<Integer, Map<String, String[]>> the #{entry.value} returns a Map<String, String[]>, so you need to iterate over it as well:

<c:forEach items="#{bean.map}" var="entry">
    <h:outputText value="Key: #{entry.key}, Values:" />
    <c:forEach items="#{entry.value}" var="nestedentry">
        <h:outputText value="Nested Key: #{nestedentry.key}, Nested Value: #{nestedentry.value}" />
    </c:forEach><br />
</c:forEach>

But in your case, the #{nestedentry.value} is actually a String[], so we need to iterate over it again:

<c:forEach items="#{bean.map}" var="entry">
    <h:outputText value="Key: #{entry.key}, Values:" />
    <c:forEach items="#{entry.value}" var="nestedentry">
        <h:outputText value="Nested Key: #{nestedentry.key}, Nested Values: " />
        <c:forEach items="#{nestedentry.value}" var="nestednestedentry">
            <h:outputText value="#{nestednestedentry}" />
        </c:forEach><br />
    </c:forEach><br />
</c:forEach>

By the way, this ought to work with rich:dataList as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...