2014-05-11 25 views
0

我使用嵌套在錶行中的表單爲每行生成一個刪除按鈕,表單的動作是一個servlet調用,然後調用remove方法在java類中。爲動態生成的表中的每一行添加一個唯一的刪除按鈕

如何向每個按鈕添加「id」值,以便將正確的汽車對象發送到要從我的數據庫中刪除的方法。

我的JSP:

<h4>Current Cars Listed</h4> 
<input type="button" value="Add Car" onclick="window.location='AddCar.jsp'"> 
<% 
List<Car> resultList = new ArrayList<Car>(); 
resultList=(List<Car>)request.getAttribute("ResultList"); 

%> 
<table border="1"> 
<thead title="Current Cars"/> 
<tr><th>Make:</th><th>Model:</th><th>Year:</th><th>Colour:</th><th>Information:</th></tr> 
<% for(int i=0; i<resultList.size(); i++){%> 

<tr><td><%=resultList.get(i).getCarMake()%></td><td><%=resultList.get(i).getModel()%></td><td><%=resultList.get(i).getCarYear()%></td> 
<td><%=resultList.get(i).getCarColour()%></td><td><%=resultList.get(i).getInformation()%></td> 
<td><form action="CarServlet" method="get" ><input type="submit" value="Remove" name="remove"></form></td></tr> 
<% }%> 


</table> 

回答

2

您可以在窗體中添加一個隱藏的價值添加ID:

<td> 
    <form action="CarServlet" method="get"> 
     <input type="hidden" name="carId" value="<%= resultList.get(i).getId() %>" /> 
     <input type="submit" value="Remove" name="remove"> 
    </form> 
</td> 

既然你已經使用請求屬性,這將是更好的stop using scriptlets at all並使用表達式語言+ JSTL。

<table> 
<thead> 
    <!-- current thead --> 
</thead> 
<tbody> 
<c:forEach items="${ResultList}" var="car"> 
    <tr> 
     <td>${car.carMake}</td> 
     <td>${car.model}</td> 
     <td>${car.carYear}</td> 
     <td>${car.carColour}</td> 
     <td>${car.information}</td> 
     <td> 
      <form action="CarServlet" method="get"> 
       <input type="hidden" name="carId" value="${car.id}" /> 
       <input type="submit" value="Remove" name="remove"> 
      </form> 
     </td> 
    </tr> 
</c:forEach> 
</tbody> 

與使用scriptlet的原始代碼相比,瞭解上述代碼如何更好地實現可讀性和可維護性。

+0

謝謝你是正確的,正是我在找什麼,但我怎麼才能在servlet中取出這個值?我試過「String carID = request.getParameter(」carId「);」但它只是給出一個空值 – SteveK

+0

@SteveK它應該與'request.getParameter(「carId」);'一起使用。你確定你在'CarServlet'的'doGet'方法中使用它嗎? –

+0

我實際上在同一個jsp中使用JSTL已經無法相信我沒有想到再次使用它,是的,它更加整潔。我發送到get方法仍然返回null – SteveK

相關問題