2016-11-29 46 views
-2

我是Java企業程序設計的初學者,現在我打算做一個食品訂單系統。我將數據庫中的所有記錄顯示在jsp頁面內的一個表中。現在我想獲取我選入數據庫的每行記錄,但問題是我只能在我的數組列表中提交最後一條記錄。有沒有人可以提供一些幫助?爲什麼我只能得到foreach循環中的最後一行值java enterprise

<table> 
     <tr> 
      <th>Name</th> 
      <th>Price</th> 
      <th>Restaurant</th> 

      <th>Add to Cart</th> 
     </tr> 
      <% 
      List<FoodRecord> foodDisplay = 
        (List<FoodRecord>) 
        session.getAttribute("foodDisplay"); 

      if(searchResult == null){ 


      for(FoodRecord foodRecord: foodDisplay) 
      { 
      %> 



     <tr> 
      <td><%=foodRecord.getName()%></td> 
      <td><%=foodRecord.getPrice()%></td> 
      <td><%=foodRecord.getRestaurant()%></td> 
      <td> 
       <form action="cost" method="post" name="menu"> 
      <input type="submit" value="Add to cart" name="order"/> 
      <% 
       session.setAttribute("id", foodRecord.getFoodId()); 
       session.setAttribute("name", foodRecord.getName()); 
       session.setAttribute("price", foodRecord.getPrice()); 

      %> 
      </form> 
      </td> 
     </tr> 

回答

3

session.setAttribute只能保存一個值。您現在編碼的方式會覆蓋這些值,並且在將頁面發佈到瀏覽器時,只有最後一個值存儲在session對象中。

如果使用隱藏域,然後每個窗體將舉行自己的價值觀,他們將被張貼在與形式:

 <form action="cost" method="post" name="menu"> 
      <input type="submit" value="Add to cart" name="order"/> 
      <input type="hidden" id="id" value="<%=foodRecord.getFoodId()%>"/> 
      <input type="hidden" id="name" value="<%=foodRecord.getName()%>"/> 
      <input type="hidden" id="price" value="<%=foodRecord.getPrice()%>"/> 
     </form> 
+0

我把你的代碼放入我的頁面,但表格的行變成空白 –

+0

非常感謝!有用!!!你救了我的一天! –

+0

修復:我刪除了一些不應該在那裏的逗號。 –

0

因爲你將其設置爲最後的值:

  session.setAttribute("id", foodRecord.getFoodId()); 
      session.setAttribute("name", foodRecord.getName()); 
      session.setAttribute("price", foodRecord.getPrice()); 

你需要的參數,而不是屬性:

<form action="cost" method="post" name="menu"> 
    <input type="submit" value="Add to cart" name="order"/> 
    <input type="hidden" value="<%=foodRecord.getFoodId()%>" name="id"/> 
    <input type="hidden" value="<%=foodRecord.getName()%>" name="name"/> 
    <input type="hidden" value="<%=foodRecord.getPrice()%>" name="price"/> 
</form> 

您會在R上的接收端讓他們equest.getParameter(「id」)等...

+0

謝謝!有用! –

相關問題