Reputation: 7647
Im populating customer data by iterating a customer list as following in the jsp.
<form action="CustomerUpdate" method="post">
<c:forEach var="listItems" items="${customers}">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<input type="submit" value="Edit" name="edit">
<input type="submit" value="Delete" name="delete"><br />
</c:forEach>
</form>
Now in the action either edit or delete each record i want to track which customer needs to be edit/delete. So in servlet how can i access the customer object which is in var listItems. If its not possible do i need to have hidden input variables with values and access them using getParameter in servlet?
Upvotes: 1
Views: 4609
Reputation: 575
in the servlet check the which button was clicked as:
if (request.getParameter("action") != null) //if action is not null
{
String action = request.getParameter("action");
String id = request.getParameter("id");
if (action.equals("edit")) //edit button clicked
{
//do your work here
}
else if (action.equals("delete")) //delete button clicked
{
//your work here
}
}
Upvotes: 0
Reputation: 7807
This is only a simple example on how to do it. Change your code in this way:
<c:forEach var="listItems" items="${customers}">
<form action="CustomerUpdate" method="post">
<input type="hidden" value="${listItems.id}" name="id">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<input type="submit" value="Edit" name="action">
<input type="submit" value="Delete" name="action"><br />
</form>
</c:forEach>
Update
Create a form element for every row, and put for every row an hidden field with the id
.
So when you press that button you will receive in the request a value that make you able to detect the row. In this way:
String id = request.getParameter("id");
String action = request.getParameter("action");
Now you know the id
and the action
type (edit or delete).
Alternative solution
Do not use the form and submit to call your action, but use a direct link.
<c:forEach var="listItems" items="${customers}">
<input type="hidden" value="" name="id">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<button onclick="window.location.href='CustomerUpdate?action=edit&id=${listItems.id}'">Edit</button>
<button onclick="window.location.href='CustomerUpdate?action=delete&id=${listItems.id}'">Delete</button>
</c:forEach>
Upvotes: 3