有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用对象数组获取数据

Possible Duplicate:
Java add all table data into list

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

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

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) 个答案

  1. # 1 楼答案

    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是有益的,因为:

    This division enables user agents to support scrolling of table bodies independently of the table head and foot. When long tables are printed, the table head and foot information may be repeated on each page that contains table data.

  2. # 2 楼答案

    你可以通过在控制器中说下面的语句来传递列表

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

    在JSP中,您可以使用以下代码(我认为您知道如何在JSP页面上使用include JSTL库)

    要使用JSTL核心库,您需要在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>
    

    希望能有帮助