Delete or put methods in thymeleaf

2020-06-03 02:50发布

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.

3条回答
劫难
2楼-- · 2020-06-03 03:28

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" />
查看更多
欢心
3楼-- · 2020-06-03 03:45

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>
查看更多
Fickle 薄情
4楼-- · 2020-06-03 03:49

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">
查看更多
登录 后发表回答