You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中@DeleteMapping触发405错误,已改用@PostMapping实现删除

Spring Boot删除请求报错及解决方法

问题场景

我在Spring Boot项目中使用@DeleteMapping注解定义了处理删除请求的控制器方法:

@DeleteMapping("/delete/{id}")
public String deleteWallet(@PathVariable("id") long id, Model model) {
    Wallet wallet = walletRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("Invalid wallet Id:" + id));
    walletRepository.delete(wallet);
    model.addAttribute("wallets", walletRepository.findAll());
    return "redirect:/";
}

同时在HTML页面中通过<a>标签发起删除请求:

<table class="table table-striped table-hover" id="productTable">
<thead>
<tr class="success">
    <th>钱包名称</th>
    <th>初始余额</th>
</tr>
</thead>
<tbody>
<tr th:each="wallet : ${wallet}">
    <td th:text="${wallet.walletName}"></td>
    <td th:text="${wallet.initialBalance}"></td>
    <td>
        <a th:href="@{/api/wallet/delete/{id}(id = ${wallet.id})}">删除</a>
    </td>
</tr>
</tbody>
</table>

点击删除按钮时触发错误:

Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]

报错原因

HTML中的<a>标签默认发起的是GET请求,但控制器方法通过@DeleteMapping声明只接收DELETE类型的请求,两者请求方式不匹配,因此抛出请求方法不支持的异常。

解决方案

1. 调整前端提交方式

将<a>标签替换为POST方法的表单,同时添加删除确认提示:

<form th:action="@{/api/wallet/delete/{id}(id=${wallet.id})}" 
th:object="${wallet}" method="post">
    <button type="submit" onClick="return confirm('确定要删除该钱包吗?')">删除</button>
</form>

2. 修改控制器注解

将控制器方法的@DeleteMapping替换为@PostMapping,使其接收POST请求:

@PostMapping("/delete/{id}")
public String deleteWallet(@PathVariable("id") long id, Model model) {
    walletService.deleteWalletById(id);
    return "redirect:/";
}

内容的提问来源于stack exchange,提问作者Stefan Jankovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:25:19