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

SpringBoot项目中@PutMapping无法正常工作的问题求助

SpringBoot + Thymeleaf PUT 请求不生效问题解决

问题根源

浏览器原生HTML表单仅支持GET和POST两种请求方法,Thymeleaf的th:method="PUT"是通过添加隐藏字段_method来模拟PUT请求的,但这个模拟需要Spring的HiddenHttpMethodFilter解析,将POST请求转换为PUT请求。如果该过滤器未生效,Spring无法识别PUT请求,导致@PutMapping方法无法触发。

解决方案

1. 确保HiddenHttpMethodFilter已启用

Spring Boot默认自动配置该过滤器,若项目中因配置变更导致失效,可通过以下方式恢复:

  • 配置文件开启:在application.properties中添加
spring.mvc.hiddenmethod.filter.enabled=true
  • 手动注册Filter:创建配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;

@Configuration
public class WebConfig {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new HiddenHttpMethodFilter();
    }
}

2. 确认表单生成了_method隐藏字段

使用th:method="PUT"时,Thymeleaf会自动生成<input type="hidden" name="_method" value="PUT"/>,可通过浏览器查看页面源码确认。若未生成,可手动添加到表单内:

<form th:method="PUT" th:action="@{/todo/edit/{id}(id=${list.id})}" th:object="${list}">
    <input type="hidden" name="_method" value="PUT"/>
    <!-- 原有表单字段 -->
</form>

3. 验证请求转换结果

提交表单时打开浏览器开发者工具(F12),查看Network标签:

  • 实际发送的是POST请求,但参数中包含_method=PUT
  • 经过Spring过滤器处理后,请求会被转换为PUT,此时@PutMapping方法即可正常触发

4. 检查Controller代码

你的Controller映射逻辑正确,注意BindingResult需紧跟在@Valid参数之后(你的代码已满足),确保参数绑定和校验逻辑无问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:24:51