Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

servlets - Java add all table data into list

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

I'm showing this example product table. I need to get this all table date into one jsp without using resultset. I tried to do up to this part:

public Product search(){
    Product p = null;
    ResultSet rs = DAO.fetch("SELECT * FROM Products");
    if (rs.next()) {
        p = new Product();
        p.setNumber(rs.getString("ProductNumber"));
        p.setName(rs.getString("ProductName"));
        p.setQty(rs.getString("ProductQty"));

    }
    return p;
}

I need to add all table data in to list or ?? and return it using method how do i do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make your search() method return a List<Product> instead of a single Product.

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

Then, in your JSP file, iterate over the returned list:

<c:forEach var="product" items="${products}">
    <!-- build your row -->
</c:forEach>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...