2013-01-10 18 views
0

我有一個類型爲HashMap<String,ArrayList<Item>>的表單中的Hashmap對象allList。我想以我的JSP頁面的形式顯示它jquery accordion。以下是我嘗試過的代碼。在JSP中處理複雜的HashMap顯示

<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; 
} 
} 
+0

請發佈「物品」的來源。 –

回答

3

你會使用第二個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>