【问题标题】:Why my Thymeleaf Delete Button does GET/POST instead of DELETE?为什么我的 Thymeleaf 删除按钮执行 GET/POST 而不是 DELETE?
【发布时间】:2021-10-06 14:14:06
【问题描述】:

我的 thymeleaf 删除按钮正在执行 GETPOST 请求,但不知道原因。

我正在使用这些启动器:

  • Spring Boot
  • Spring 安全
  • Spring JPA
  • Spring Web

我的控制器:

@Controller
public class UserController {

// [...]

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

        userDeletionService.deleteUserById(id);

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

这是第一个尝试使用传递给模板的属性(user)的按钮:

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

遇到 error 405,我们可以注意到它执行了 GET

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

在这里,我正在尝试一个 sedond 按钮:

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

再次因错误 405 而失败,但这一次,它执行了 POST

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

【问题讨论】:

  • 链接 (&lt;a&gt;) 总是GET,表单可以是GETPOST。要发出DELETE,您必须使用 JavaScript (AJAX)。
  • @slauth 非常感谢您清晰的解释!它应该被更多地引用,而不是在调试上浪费太多时间。我会试试这个,然后马上回来。
  • 再次感谢@slauth。对我有用的是 Raphael Roussis 在以下链接上的回答(也感谢他):stackoverflow.com/questions/38370011/…

标签: java spring-boot thymeleaf


【解决方案1】:

HTML 默认只能使用 GET 或 POST。 Spring Boot 和 Thymeleaf 支持通过 HiddenHttpMethodFilter 解决方法。

要使用它,你需要做两件事:

  1. 在您的表单中添加th:method="delete"
<form th:method="delete" ... >

Thymeleaf 会自动插入隐藏的输入,如下所示:

<input type="hidden" name="_method" value="delete" />
  1. 在 Spring Boot 中启用过滤器。最简单的方法是将其添加到application.properties
spring.mvc.hiddenmethod.filter.enabled=true

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 2021-12-18
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多