在RESTful风格的接口设计中,DELETE请求专门用于删除指定资源,但是HTML原生的表单元素仅支持GET和POST两种提交方法,无法直接发送DELETE请求。在Spring Boot项目中要实现DELETE请求的表单提交,需要结合前端适配和后端配置共同完成,既要符合HTTP协议规范,也要保证功能正常可用。

前端表单的处理方式
由于HTML表单不支持直接设置method为DELETE,最常用的是通过隐藏表单字段传递真实请求方法,再配合Spring的过滤器进行转换。首先在表单中设置method为POST,同时添加一个隐藏的input字段,name为_method,value为DELETE。
<form action="/user/delete/1" method="POST">
<!-- 隐藏字段指定真实请求方法 -->
<input type="hidden" name="_method" value="DELETE"/>
<button type="submit">删除用户</button>
</form>
这里需要注意,表单的action属性填写的是DELETE接口对应的路径,隐藏字段的name必须是_method,Spring默认会识别这个字段来转换请求方法。
后端Spring Boot配置
Spring Boot默认没有提供表单方法转换的过滤器,需要手动添加HiddenHttpMethodFilter到容器中,这个过滤器会读取请求中的_method参数,将POST请求转换为对应的HTTP方法。
配置过滤器
可以在配置类中手动注册过滤器:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean<HiddenHttpMethodFilter> hiddenHttpMethodFilter() {
FilterRegistrationBean<HiddenHttpMethodFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new HiddenHttpMethodFilter());
// 设置过滤器拦截所有请求
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
编写DELETE接口
配置完成后,就可以在Controller中编写标准的DELETE请求接口,使用@DeleteMapping注解标识:
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@DeleteMapping("/user/delete/{id}")
public String deleteUser(@PathVariable Long id) {
// 这里编写删除用户的业务逻辑,比如操作数据库删除对应id的用户
System.out.println("删除用户,id为:" + id);
return "删除成功";
}
}
注意事项
- 隐藏字段的name必须是
_method,value需要大写,比如DELETE、PUT等,否则过滤器无法正确识别。 - 如果项目使用了Spring Security,需要额外配置允许表单提交POST请求到DELETE接口,避免被安全框架拦截。
- 这种方式仅适用于表单提交场景,如果是前后端分离项目,前端可以直接发送DELETE请求,不需要使用隐藏字段的方式。
- 不要在生产环境中直接暴露删除接口,建议添加权限校验,避免未授权的删除操作。
常见问题排查
如果提交表单后后端没有匹配到DELETE接口,可以先检查过滤器是否生效,查看请求头中的_method参数是否正确传递。也可以通过在过滤器中打印日志,确认请求方法是否被正确转换。如果接口返回405错误,通常是请求方法不匹配,需要检查@DeleteMapping的路径和表单的action路径是否一致。
Spring_BootDELETE请求表单提交HTTP方法修改时间:2026-07-03 10:18:14