Spring Boot/JPA:DeleteMapping删记录遇405错误求助
问题原因分析
你遇到的HTTP Status 405 – Method Not Allowed错误,核心原因是请求方法不匹配:
- Thymeleaf中的
<a>标签点击后默认发送GET请求 - 你的Controller方法使用
@DeleteMapping注解,仅接收HTTP DELETE方法,因此服务器拒绝该请求
解决方案
方案1:用表单模拟DELETE请求(推荐,符合REST规范)
Spring MVC支持通过_method参数将POST请求转换为DELETE请求(Spring Boot 2.x及以上默认启用HiddenHttpMethodFilter,无需额外配置)。修改Thymeleaf代码为表单:
<td> <form th:action="@{/delete/{idUser}(idUser=${user.idUser})}" method="post"> <input type="hidden" name="_method" value="delete"/> <button type="submit">Delete user</button> </form> </td>
Controller代码无需修改,保持原@DeleteMapping即可。
方案2:修改Controller为接收GET请求(仅用于测试,不推荐生产环境)
将Controller的@DeleteMapping替换为@GetMapping,让它接收GET请求:
@GetMapping("/delete/{id}") public String deleteMailbox(@PathVariable("id") Long id) { repo.deleteById(id); return "redirect:/userList?success"; }
⚠️ 注意:这种方式违背REST设计规范,GET请求不应用于修改/删除资源,可能被浏览器缓存、爬虫误触发,导致数据意外丢失,仅适合临时测试。
方案3:用JavaScript发送DELETE请求(适合无刷新场景)
通过前端JS发送DELETE请求,实现无刷新删除:
<td> <button onclick="deleteUser([[${user.idUser}]])">Delete user</button> </td> <script> function deleteUser(userId) { if(confirm("确定要删除该用户吗?")) { fetch(`/delete/${userId}`, { method: 'DELETE' }).then(response => { response.ok ? window.location.href = "/userList?success" : alert("删除失败"); }).catch(() => alert("请求出错,请重试")); } } </script>
Controller保持原@DeleteMapping不变。
内容的提问来源于stack exchange,提问作者Djorkaeff
相关产品推荐
相关产品推荐

