user3128455
user3128455

Reputation: 811

Delete or put methods in thymeleaf

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.

Upvotes: 22

Views: 40756

Answers (6)

Giovannisc
Giovannisc

Reputation: 47

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

try this instead:

spring.mvc.hiddenmethod.filter.enabled=true

Upvotes: 1

Metehan Altuntas
Metehan Altuntas

Reputation: 85

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

Upvotes: 0

enesoral
enesoral

Reputation: 583

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.

Upvotes: 18

bench_doos
bench_doos

Reputation: 169

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>

Upvotes: 2

marcok
marcok

Reputation: 1060

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">

Upvotes: 34

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

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" />

Upvotes: 10

Related Questions