I am trying to delete an entity on a page via a delete link (a href) or delete button (form). I am using delete button since a link calls for a "GET" instead of a "POST"
This is the JSP code which intends on doing that:
<td><form:form method="DELETE" action="/client/invoices/${invoice.id}"><input type="submit" value="delete"></form:form></td>
The resulting html is this:
<td><form id="command" action="/client/invoices/9" method="post"><input type="hidden" name="_method" value="DELETE"/><input type="submit" value="delete"></form></td>
So, I'm pretty happy. It has _method which indicates that it is a DELETE action. Here is my controller code:
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
invoiceServiceHibernate.removeInvoice(id);
return "redirect:/invoices";
}
So, what happens is that this method is not called. I have another method which does a POST to create an invoice and clicking the delete button instead created an invoice. My guess is that the controller looks at the servlet as a POST request and uses the first method which handles a POST request which in this case is to create a new invoice.
I try to make this "RESTful" so I want this to be /invoice/id
and using POST, PUT, DELETE, GET
but I am not sure how to code that in the controller using Spring MVC.
I am able to get this to work by appending "verbs" such as /invoices/id/delete
and setting up the controller as
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
Note, the RequestMethod.POST but since the map values explicitly have /id/delete
, it does not use the default POST which is mapped to /invoices
and /invoices/id
.
I hope I am clear. If anyone have any suggestions or sample code (strongly preffered), I would appreciate it. I've read these SO links for references: Link1 Link2 Link3