使用对象数组获取数据

时间:2012-10-28 13:22:07

标签: java jsp servlets

  

可能重复:
  Java add all table data into list

+--------+-------+-----+
|  Name  |number |qty  |
+--------+-------+-----+
|   ab   |   5   |  7  |
+--------+-------+-----+ 
|   cd   |   1   |  6  |
+--------+-------+-----+ 
|   ef   |   0   |  9  |
+--------+-------+-----+ 
|   gh   |   8   |  2  |
+--------+-------+-----+ 

我将Product中的所有数据添加到数组列表中,如下所示

public List<Product> search(){
    List<Product> products = new ArrayList<Product>();
    ResultSet rs = DAO.fetch("SELECT * FROM Products");
    while (rs.next()) {
        product = new Product();
        product.setNumber(rs.getString("ProductNumber"));
        product.setName(rs.getString("ProductName"));
        product.setQty(rs.getString("ProductQty"));
        products.add(product);
    }
    return products;
}

如何使用此功能在我的jsp中打印所有名称?

2 个答案:

答案 0 :(得分:4)

您可以通过在控制器中说出以下声明来传递列表

List <Product> products = dao.search();
request.setAttribute("Products", products);

并且,在您的JSP中,您可以使用以下代码(我在考虑您知道如何在JSP页面上使用包含JSTL库)。

要使用JSTL Core库,您需要在JSP中添加以下行

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

然后您可以显示遍历传递的列表以显示所有产品。

<table>
   <tr>
     <th>Name</th>
     <th>Number</th>
     <th>Quantity</th>
   </tr>
 <c:forEach items="${Products}" var="product">
    <tr>
      <td><c:out value="${product.name}" /></td>
      <td><c:out value="${product.number}" /></td>
      <td><c:out value="${product.qty}" /></td>
    </tr>
  </c:forEach>
</table>

希望它有所帮助。

答案 1 :(得分:0)

products添加到appropriate scope并转发到您的jsp页面:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.name}</td>
                <td>${product.number}</td>
                <td>${product.qty}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>

顺便说一下,在这种情况下使用thead and tbody是有益的:

  

此划分使用户代理能够支持滚动表体   独立于桌子的头部和脚部。长桌时   打印时,可以在每个上重复表头和脚的信息   包含表格数据的页面。

相关问题