繁体   English   中英

在JSP中处理复杂的HashMap显示

[英]Handling complex HashMap display in JSP

我有一个Hashmap对象allList ,形式为HashMap<String,ArrayList<Item>> 我想将其显示在我的JSP页面上,为jquery手风琴 以下是我尝试过的代码。

<script type="text/javascript">
$(function() {
    $( "#accordion" ).accordion({
        heightStyle: "fill",
        collapsible: true
     });
});

</script>

<div id="accordion">
       <c:forEach items="${allList}" var="myLs">
    <h3>${myLs.key}</h3>
    <div>${myLs.value}</div> // This is giving me toString of Item.
</c:forEach>
</div>

我能够将hashmap的键显示为标题。 但是我无法弄清楚如何将相应的arraylist对象显示为有序列表。 请帮帮我。

public class Item implements java.io.Serializable, Comparable<Object> {
    private Long id;
    private String itemName;
    private Double unitCost;
    private String status;
    private int quantity;
    public Item() {
    }
        //getters and setters
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Item)) {
            return false;
        }
        final Item item = (Item) o;
        if (getItemName() != null && item.getItemName() == null)
            return false;
        if (getItemName() == null && item.getItemName() != null)
            return false;
        if (!getItemName().equals(item.getItemName()))
            return false;
        return true;
    }
    public int hashCode() {
            return getItemName().hashCode();
    }

    public String toString() {
       return "Item - Id: "+getId+", Name : "+getItemName;
    }
    public int compareTo(Object o) {
       if (o instanceof Item) {
           return getItemName().compareTo(((Item) o).getItemName());
       }
       return 0;
    }
}

您将使用第二个forEach循环:

<div id="accordion">
    <c:forEach items="${allList}" var="myLs">
        <h3>${myLs.key}</h3>
        <div>
            <c:forEach var="item" items="${myLs.value}">
                ${item.foo}, ${item.bar}  <br/>
            </c:forEach>
        </div>
    </c:forEach>
</div>

我认为您会因错误的命名选择而感到困惑。 您应该为Map<String, ArrayList<Item>> allList ,因为它不是列表,而是地图。 而且,您不应将映射条目命名为myLs因为它并不代表任何含义。 我将代码重构为(假设地图中的键代表项目的所有者)

<div id="accordion">
    <c:forEach items="${itemsPerOwner}" var="itemsPerOwnerEntry">
        <h3>${itemsPerOwnerEntry.key}</h3>
        <div>
            <c:forEach var="item" items="${itemsPerOwnerEntry.value}">
                ${item.foo}, ${item.bar}  <br/>
            </c:forEach>
        </div>
    </c:forEach>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM