为什么我只能得到foreach循环中的最后一行值java enterprise

问题描述:

我是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> 

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

修复:我删除了一些不应该在那里的逗号。 –

因为你将其设置为最后的值:

  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

谢谢!有用! –