Search code examples
htmlspringmappingthymeleafspring-thymeleaf

How can you use Spring DeleteMapping with HTML-form or etc?


I want to use DeleteMapping in the Spring-Controller-Class:

@DeleteMapping("/{id}")
private void deleteEmployee(@PathVariable Integer id)
{
    repository.deleteById(id);
}

I want to read in a id in html and delete the employee. How can I use HTML to perform this method?


Solution

  • In a form, a browser will only send methods GET and POST. If you want to send a DELETE, you have 2 options.

    1. Use Javascript/AJAX. You can set the http method on a AJAX request and the browser will obey this.

    2. Fake a DELETE using the HiddenHttpMethodFilter. By putting a hidden field in your form, Spring will fake turning this request into a DELETE and call the correct endpoint.