Programming Spring MVC controller and jsp for HttpDelete

I am trying to delete an object on a page using a delete (href) or delete (form) link. I use the delete button because the link calls "GET" instead of "POST"

This is the JSP code that intends to do this:

<td><form:form method="DELETE" action="/client/invoices/${invoice.id}"><input type="submit" value="delete"></form:form></td> 

The result is html:

 <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 am very happy. It has a method that indicates that this 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, this method is not called. I have another method that does POST to create an invoice, and clicking the delete button instead creates an invoice. I assume that the controller looks at the servlet as a POST request and uses the first method that processes the POST request, which in this case should create a new invoice.

I'm trying to make it "RESTful", so I want it to be /invoice/id and using POST, PUT, DELETE, GET , but I'm not sure how to encode this in the controller using Spring MVC.

I can make this work by adding "verbs" such as /invoices/id/delete and setting up the controller as

 @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST) 

Please note that RequestMethod.POST, but since the map values ​​are explicitly /id/delete , it does not use the default POST, which maps to /invoices and /invoices/id .

I hope I get it. If anyone has any suggestions or code examples (highly recommended), I would appreciate it. I read these SO links for links: Link1 Link2 Link3

+6
source share
2 answers

Have you installed HiddenHttpMethodFilter in your web.xml? This filter converts published method parameters to HTTP methods and allows you to support method conversion in Spring MVC form tags.

 <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <servlet-name>servletName</servlet-name> </filter-mapping> 
+7
source

Here is the equivalent in Java Config (requires Servlet API 3.0 +)

  servletContext .addFilter("HiddenHttpMethodFilter", HiddenHttpMethodFilter.class) .addMappingForUrlPatterns(null, false, "<your desired mapping here>"); 
+2
source

Source: https://habr.com/ru/post/900134/


All Articles