视图列表或单个对象的公共页面

时间:2012-01-17 10:08:23

标签: jsp servlets jstl

我想写一个查看数据列表或单个对象的公共页面。

在控制器中:

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;

这是一个非常简单的例子,我的应用程序必须查看该对象的大量数据,并使用相同的代码制作两个相似的页面。 如何解决这个问题呢?将此单个对象添加到列表中还是有另一种解决方案?

2 个答案:

答案 0 :(得分:3)

好像你想要传递单个元素而不是列表。解决此问题的一种方法是使用单个元素构建列表并传递它。使用以下命令创建只包含一个元素的列表。

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

答案 1 :(得分:1)

这是因为jstl forEach标记期待List,并且您传递的是单个对象。 尝试传递一个元素列表:

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