17

I would like to call @RequestMapping(value = "", method = RequestMethod.DELETE) in spring from thymeleaf form.

Is there any possibility to call delete or put request mapping methods from thymeleaf?

please give your suggestion on this.

Rogue
  • 11,105
  • 5
  • 45
  • 71
user3128455
  • 741
  • 2
  • 7
  • 9

6 Answers6

33

You could use th:method for this:

<form th:object="${commandObject}" th:action="@{/urlToCall}" th:method="delete">

This will generate a hidden input element, which will be picked up by Spring MVC:

<input type="hidden" name="_method" value="delete">
marcok
  • 1,050
  • 9
  • 13
  • 2
    For me I had to add `spring.mvc.hiddenmethod.filter.enabled=true`to my `application.properties` file to work. – Gothiquo Sep 20 '22 at 09:08
16

When we use th:method="PUT", thymeleaf creates hidden input as in the screenshot below. Then HiddenHttpMethodFilter converts posted method parameters into HTTP methods.

httpmethodfilter-conversion

HiddenHttpMethodFilter disabled by default in Spring Boot 2.2.

You can enable this by adding spring.mvc.hiddenmethod.filter.enabled=true to your application.properties file.

enesoral
  • 523
  • 4
  • 16
10

Thymeleaf is an HTML template engine. HTML does not support put or delete HTTP methods for its method attribute. So, no, you can't. However, you have alternatives.

You can use javascript to send the request asynchronously. In that case, you can send any type of HTTP request.

You can also use a HiddenHttpMethodFilter with a hidden _method=put <input> element as described here. Something like

<input name="_method" type="hidden" value="PUT" />
Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
2

Only solution I've found - use js:

Add scrypt:

<script th:inline="javascript">
    function sendDelete(url) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("DELETE", url, true);
        xhttp.onload = function () {
            let responseURL = xhttp.responseURL;
            console.log("Redirecting to:", responseURL);
            window.location.replace(responseURL);
        };
        xhttp.send();
    }
</script>

and add calling link (or change to button):

<a type="button" th:with="url = @{<your_url>}" th:onclick="sendDelete([[${url}]])">Delete</a>
bench_doos
  • 172
  • 11
0

I am currently doing research on this subject. As far as I understand, we can perform these operations without the need to use PUT or DELETE methods. So you may not need to use JavaScript or anything else. These operations can be done using only Thymeleaf, HTML and Spring.

If someone has come here for this and is looking for such a solution, please check the post at this address. It was useful for me.

Here's link: Spring Boot CRUD Thymeleaf

0

In my case, I use it and it works well.:

try this instead:

spring.mvc.hiddenmethod.filter.enabled=true