Question

I am using a form nested inside a table row to generate a remove button for each row, the action of the form is a servlet call which will then call the remove method in a java class.

How do I add the "id" value to each button so it will send the correct car object to the method to be removed from my database.

My 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>
Was it helpful?

Solution

You may add a hidden value inside the form to add the 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>

Since you're already using request attribute, it would be better to stop using scriptlets at all and use Expression Language + 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>

See how code above is better for readability and maintainability compared to your original code that uses scriptlets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top