簡體   English   中英

如何在JSP中迭代列表對象?

[英]How can I iterate list object in JSP?

我有ShoppingCart課程:

package shoppingcart;

import models.CD;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ShoppingCart {

    private List<CD> shoppingCartItemList ;
    private long totalPrice ; 

    public ShoppingCart() 
    {
        shoppingCartItemList = new ArrayList<CD>() ;
        totalPrice = 0 ; 
    }

    public void addCdToCart(CD cd)
    {
        shoppingCartItemList.add(cd) ;
        totalPrice += cd.getPrice();
    }

    public List<CD> getShoppingCartItems() 
    {
        return this.shoppingCartItemList ;
    }

    public long getTotalPrice() 
    {
        return totalPrice;
    }

}

我在Servlet中使用此類:

ShoppingCart shoppingCart = new ShoppingCart();

CD cd = new CD(1, "DAVID", 10, 1);
shoppingCart.addCdToCart(cd);

request.getSession().setAttribute("shoppingCart", shoppingCart);
request.setAttribute("servletMessage", "CD added to Cart");     

如您所見,我有一個列表,我必須在jsp中對其進行迭代。 我在jsp中導入ShoppingCard類:

<%@ page import="shoppingcart.ShoppingCart"%>
<c:forEach items="${shoppingCart.getShoppingCartItems}" var="cart">
<form method="POST"     action="${pageContext.request.contextPath}/removeFromCart">
<input type="hidden" name="cdId" value="${cart.title}" />
<tr>
<td><c:out value="${cart.title}" /></td>
<td align="center"><c:out value="${cart.category}" /></td>
<td align="center"><c:out value="${cart.price}" /></td>
<td align="center" width="25%"><input type="submit" value="Remove"  name="action" style="height:30px; width: 70px;font-size:10pt;"></td>
</tr>
</form>
</c:forEach>

我收到此錯誤:

org.apache.jasper.el.JspPropertyNotFoundException: /myCart.jsp(85,4) '${shoppingCart.getShoppingCartItems}' Property 'getShoppingCartItems' not found on type shoppingcart.ShoppingCart. What can I solve this problem?

我應該改變點什么嗎?

由於添加了額外的代碼而進行了編輯。

購物車存儲在名為“ shoppingCart”的屬性中。 所以應該像

<c:forEach items="${shoppingCart.xxx}" ...

其中xxx是允許訪問ShoppinCart實例內的列表的屬性。 但是您沒有這樣的財產。 因此,在ShoppingCart中添加以下方法:

 public List<CD> getElements() {
     return this.shoppingCartItemList;
 }

和使用

<c:forEach items="${shoppingCart.elements}" ...

注意,將“ shoppingCartItemList”命名為類“ ShoppinCart”的屬性是多余且冗長的。 這就是為什么我選擇來命名吸氣getElements() shoppingCart.elements比更容易閱讀和自然shoppingCart.shoppingCartItemList 您還應該將私有字段重命名為elements

我建議您使用JSTL來迭代JSP中的對象

這是類似的情況: JSTL遍歷對象列表

這是一個示例: http : //www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags

這是一個jstl教程: http : //www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

它擁有更多東西來擁有更好的源代碼。 我希望這可以幫助您...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM