0

My thymeleaf delete button is executing either a GET or a POST request without understanding why.

I'm using those starters:

  • Spring Boot
  • Spring Security
  • Spring JPA
  • Spring Web

My controller:

@Controller
public class UserController {

// [...]

@DeleteMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id) {

        userDeletionService.deleteUserById(id);

        return "redirect:/users/list";
    }
}

Here's the first tried button using an attribute(user) passed to the template:

<a th:href="@{'/users/delete/{id}'(id=${user.id})}" class="btn btn-danger btn-sm">Delete</a>

Falling on error 405 and we can notice that it did a GET:

DEBUG org.springframework.security.web.FilterChainProxy - Secured GET /users/delete/18    
DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 405 METHOD_NOT_ALLOWED

Here, I'm trying a sedond button:

<form action="#" th:action="@{'/users/delete/{id}'(id=${user.id})}" th:method="delete" >
        <input type="hidden" name="_method" value="delete" />
        <button type="submit" id="submitButton"> </button>
</form>

Falling again on error 405 but, this time, it did a POST:

DEBUG org.springframework.security.web.FilterChainProxy - Secured POST /users/delete/18
DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 405 METHOD_NOT_ALLOWED
dariosicily
  • 4,239
  • 2
  • 11
  • 17
David
  • 37
  • 7

1 Answers1

0

HTML can only use GET or POST by default. Spring Boot and Thymeleaf support a workaround via the HiddenHttpMethodFilter.

To use it, you need to do 2 things:

  1. Add th:method="delete" on your form:
<form th:method="delete" ... >

Thymeleaf will automatically insert a hidden input like this:

<input type="hidden" name="_method" value="delete" />
  1. Enable the filter in Spring Boot. The easiest way is adding this to application.properties:
spring.mvc.hiddenmethod.filter.enabled=true
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211