【发布时间】:2014-01-17 03:01:44
【问题描述】:
我的响应对象包含地图的 getter 和 setter -
public class DataResponse {
private Map<String, List<String>> attributes = new LinkedHashMap<String, List<String>>();
public Map<String, List<String>> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, List<String>> attributes) {
this.attributes = attributes;
}
}
在上面的对象中,我有一个Map of String and List<String>。在地图中,keys 是我的表头,而地图中的value 是该表头的表数据。
假设这是地图中的值 -
FirstName is the Key in the same Map
DAVID, RON, HELLO are the values in the map as the List for that key.
同样,
LastName is the Key in the same Map
JOHN, PETER, TOM are the values in the map as the List for the `LastName` key.
那么我的表格应该是这样的
FirstName LastName
David JOHN
RON PETER
HELLO TOM
我需要动态生成上表,因为我将dataResponse 对象传递给我的 JSP 页面,如下所述 -
DataResponse dataResponse = some_code_here;
req.setAttribute("data", dataResponse);
WebUtil.forward(req, resp, this, "/admin/test.jsp");
下面是我在 JSP 中的表格,我使用上面的对象生成上述格式的表格
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR>
<c:forEach var="h" items="${data.attributes}">
<TH>${h.key}</TH>
</c:forEach>
</TR>
//iterate again
<c:forEach var="h" items="${data.attributes}">
//h.value is ArrayList so we can iterate with c:forEach
<c:forEach var="headers" items="${h.value}">
<TR>
<TD>${headers}</TD>
</TR>
</c:forEach>
</c:forEach>
</TABLE>
但不知何故,我的表格并没有按照我在上面的示例中尝试显示的方式显示。所有键都正确显示在表头中,但所有值仅显示在第一列中。
所有键的列表大小都相同。
有没有想过如何做到这一点?
更新:-
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR>
<c:forEach var="h" items="${data.attributes}">
<TH>${h.key}</TH>
</c:forEach>
</TR>
//iterate again
<c:forEach var="h" items="${data.attributes}">
<TR>
<c:forEach var="headers" items="${h.value}">
<TD>${headers}</TD>
</c:forEach>
</TR>
</c:forEach>
</TABLE>
这给了我 -
FirstName LastName
David RON HELLO
JOHN PETER TOM
【问题讨论】:
-
将你的第二个循环移动到
<TR>...</TR> -
也不是这样工作的。我已经尝试过这些步骤。查看我更新的问题..
-
我认为你需要将 td 移出 --
${headers} -
类似这样的
<c:forEach var="h" items="${data.attributes}"> <TR> <TD> <c:forEach var="headers" items="${h.value}"> ${headers} </c:forEach> </TD> </TR> </c:forEach>不行.. :( -
您组织地图的方式——同一对象的字段存储在不同的键下,因此存储在不同的列表中——不允许这种形式的迭代。唯一将
FistName和LastName“链接”在一起的是它们在各自列表中的位置。
标签: java jsp servlets html-table