2012-01-17 31 views
0

我想編寫查看數據列表或單個對象的常用頁面。查看列表或單個對象的常見頁面

在控制器:

ArrayList<Table> tables; 
request.setAttribute("tables", tables); 

和JSP:

<table > 
    <c:forEach var="table" items="${tables}"> 
     <tr> 
      <th><c:out value=" ${table.name}" /></th> 
     </tr> 
    </c:forEach> 
</table> 

顯示良好。

當我通過單一的對象 -

Table table; 
request.setAttribute("table", table); 

不顯示任何東西;

比我嘗試過

Table tables; 
request.setAttribute("tables", tables); 

我有錯誤

Don't know how to iterate over supplied "items" in &lt;forEach&gt; 

這是一個非常簡單的例子,我的應用程序必須查看大量該對象的數據,並與兩個相似的網頁相同的代碼很愚蠢。 如何解決這個問題?將這個單個對象添加到列表中還是有另一個解決方案?

+0

您應該必須將該單個「表」對象添加到列表中。 – adatapost 2012-01-17 10:12:30

回答

3

看來你想傳遞單個元素而不是列表。解決這個問題的一種方法是用單個元素構建一個列表並傳遞它。使用以下內容創建只有一個元素的列表。

List<Table> tables = Collections.singletonList(table); 
+0

感謝您的回答。 – Ifozest 2012-01-17 10:26:41

1

這是因爲JSTL forEach標籤期待一個列表,並且您傳遞一個對象。 嘗試傳遞一個元素列表:

Table table; 
ArrayList<Table> tables=new ArrayList<Table>(); 
tables.add(table) 
request.setAttribute("tables", tables); 
+2

謝謝你的回答,但我會效仿Harry Joy的例子。 – Ifozest 2012-01-17 10:26:30

+1

@Viachaslau的確,我也是。它比我的方式更清潔:) – 2012-01-17 10:30:28