2026-01-19 如何在Spring Boot中正确实现DELETE请求的表单提交 技术 EthanWu html原生表单不支持delete方法,仅支持get和post;需通过spring security的_csrf参数配合_method隐藏字段模拟delete请求,否则浏览器会默认以get方式提交导致405错误。 在Spring Boot(基于Spring Framework)中,前端HTML表单无法直接发送DELETE、PUT等非标准HTTP方法——这是HTML规范限制,与Spring配置无关。当您在Thymeleaf模板中设置 method=”delete”(如 ),浏览器会忽略该值,并默认以GET方式提交表单,从而触发 HttpRequestMethodNotSupportedException: Request method ‘GET’ not supported 错误。 ✅ 正确做法:使用Spring提供的HTTP方法伪装(Method Overriding)机制: 后端保持 @DeleteMapping 不变(推荐语义清晰): @DeleteMapping("/conductor/confirmDelete") public String borrarConfirmado(@Valid Conductor driver, BindingResult result, Model model) { condService.borrarPersona(driver); return "redirect:/conductor/list"; } 前端表单必须改为 method=”post”,并添加隐藏字段 _method=DELETE 和CSRF令牌(Spring Security启用时必需): Play.ht 根据文本生成多种逼真的语音 下载 Nombre: Apellido: Cedula: Teléfono: Dirección: Borrar ⚠️ 注意事项: 必须确保项目已引入 spring-boot-starter-web(默认包含 HiddenHttpMethodFilter);Spring Boot 2.0+ 默认自动注册该过滤器,无需额外配置。 若使用Spring Security,_csrf字段不可省略(Thymeleaf会自动渲染,前提是启用了CSRF且模板中引用了${_csrf})。 不要尝试用JavaScript手动发DELETE请求(如fetch())来绕过——虽然可行,但违背了服务端渲染+表单语义的设计初衷;如需AJAX,应单独设计API接口(返回JSON)并配合前端JS处理。 @DeleteMapping 方法中接收@Valid Conductor driver需确保表单字段与实体属性严格匹配(含ID),否则校验可能失败或绑定为空。建议改用路径参数传ID更安全: @DeleteMapping("/conductor/confirmDelete/{id}") public String borrarConfirmado(@PathVariable Long id, Model model) { condService.borrarPersonaById(id); // 推荐:按ID删除,避免表单绑定风险 return "redirect:/conductor/list"; } 总结:HTML表单的method属性仅接受get或post;Spring通过_method参数+HiddenHttpMethodFilter将POST请求“重写”为DELETE/PUT等,这是标准且安全的解决方案。切勿依赖无效的method=”delete”,也无需自定义过滤器或禁用CSRF。 https://www.php.cn/faq/2000001.html