Spring中使用DELETE提交表单却提示GET方法不支持的问题求助
问题原因与解决方案
问题根源
浏览器原生HTML表单仅支持GET和POST两种请求方法,你在表单中设置的method="delete"不会被浏览器识别,最终会默认以GET方法提交请求。而你的控制器仅通过@DeleteMapping映射了DELETE请求,因此触发Request method 'GET' not supported错误。
另外,当前表单仅展示司机数据,没有提交司机的id字段,即使请求方法正确,服务层也无法拿到要删除的司机ID,删除操作会失败。
修复步骤
修正表单请求方法
将表单的提交方式改为POST,并通过_method隐藏域告知Spring MVC要转换为DELETE请求——Spring的HiddenHttpMethodFilter会自动处理这种转换,匹配你的@DeleteMapping接口。用Thymeleaf可以更简洁实现:直接使用
th:method="delete",它会自动生成_method隐藏域,无需手动编写。添加司机ID的隐藏提交字段
在表单中添加一个隐藏的input标签,绑定司机的id属性,确保提交时能传递要删除的司机ID。
修改后的表单代码示例:
<!DOCTYPE html> <html> <head> <title>Confirmar Eliminación</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div> <h1>Conductor</h1> <!-- 用th:method="delete"自动处理请求方法转换 --> <form th:action="@{/conductor/confirmDelete}" th:object="${conductor}" th:method="delete"> <!-- 隐藏提交司机ID,确保服务层能拿到删除目标 --> <input type="hidden" th:field="*{id}" /> <label for="driverFirstName">Nombre: </label> <label th:text="*{firstName}" id="driverFirstName"></label><br> <label for="driverLastName">Apellido: </label> <label th:text="*{lastName}" id="driverLastName"></label><br> <label for="driverCedula">Cedula: </label> <label th:text="*{cedula}" id="driverCedula"></label><br> <label for="driverTelefono">Telefono: </label> <label th:text="*{telefono}" id="driverTelefono"></label><br> <label for="driverDireccion">Direccion: </label> <label th:text="*{direccion}" id="driverDireccion"></label><br> <button type="submit">Borrar</button> </form> </div> <a th:href="@{/conductor/list}">Cancelar</a> </body> </html>
- 确认Spring Boot配置(可选)
Spring Boot 2.x及以上版本默认启用了HiddenHttpMethodFilter,如果你的项目手动关闭了该过滤器,需要在配置类中重新启用:
@Configuration public class WebConfig implements WebMvcConfigurer { @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter() { return new HiddenHttpMethodFilter(); } }
额外检查
确保你的服务层borrarPersona(driver)方法是通过司机ID执行删除逻辑的,比如:
public void borrarPersona(Conductor driver) { conductorRepository.deleteById(driver.getId()); }
内容的提问来源于stack exchange,提问作者AFAV
相关产品推荐
相关产品推荐

