Spring MVC 在Thymeleaf中删除或放置方法

1l5u6lss  于 2023-08-06  发布在  Spring
关注(0)|答案(6)|浏览(149)

我想在Spring从百里香叶形式调用@RequestMapping(value = "", method = RequestMethod.DELETE)
有没有可能从thymeleaf调用delete或put请求Map方法?
请就这件事给予你的建议。

qltillow

qltillow1#

你可以使用th:method来实现:

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

字符串
这将生成一个隐藏的input元素,它将被Spring MVC拾取:

<input type="hidden" name="_method" value="delete">

yqkkidmi

yqkkidmi2#

当我们使用th:method="PUT"时,thymeleaf会创建隐藏输入,如下面的屏幕截图所示。然后HiddenHttpMethodFilter将posted方法参数转换为HTTP方法。


的数据
HiddenHttpMethodFilter在Sping Boot 2.2中默认禁用。
您可以通过将spring.mvc.hiddenmethod.filter.enabled=true添加到application.properties文件来启用此功能。

ehxuflar

ehxuflar3#

Thymeleaf是一个HTML模板引擎。HTML不支持putdelete HTTP方法用于其method属性。所以,不,你不能。不过,您还有其他选择。
可以使用JavaScript异步发送请求。在这种情况下,您可以发送任何类型的HTTP请求。
您也可以将HiddenHttpMethodFilterhidden_method=put<input>元素搭配使用,如here所述。比如说

<input name="_method" type="hidden" value="PUT" />

字符串

yyhrrdl8

yyhrrdl84#

我找到的唯一解决方案-使用js:
添加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>

字符串
并添加呼叫链接(或更改为按钮):

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

rta7y2nd

rta7y2nd5#

我目前正在研究这个问题。据我所知,我们可以执行这些操作,而不需要使用PUTDELETE方法。因此,您可能不需要使用JavaScript或其他任何东西。这些操作只能使用Thymeleaf,HTML和Spring来完成。
如果有人为此来到这里并正在寻找这样的解决方案,请检查此地址的帖子。这对我很有用。
这里的链接:Spring Boot CRUD Thymeleaf

vc9ivgsu

vc9ivgsu6#

在我的情况下,我使用它,它工作得很好。:
试试这个:
spring.mvc.hiddenmethod.filter.enabled=true

相关问题