传统 HTML 表单如何支持PUT DELETE 方法提交请求
HiddenHttpMethodFilter
在 Spring 应用中主要用于支持 HTML 表单提交时使用 PUT、DELETE 等 HTTP 方法。由于标准的 HTML <form>
标签只支持 GET 和 POST 方法,因此如果想使用其他 HTTP 方法(如 PUT 或 DELETE),可以通过在表单中添加一个隐藏字段 _method
来指定想要使用的 HTTP 方法,并让 HiddenHttpMethodFilter
处理这个请求。
下面是一个具体的使用案例:
前端代码
假设有一个简单的 HTML 表单用于删除某个资源:
<form action="/resources/1" method="POST">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="Delete Resource"/>
</form>
在这个例子中,即使表单的 method
属性被设置为 POST
,但由于存在一个名为 _method
的隐藏输入框且其值设为了 "DELETE"
,这表示实际希望发起的是一个 DELETE 请求。
后端配置
为了使上述前端代码工作,需要确保 Spring 应用程序已经配置了 HiddenHttpMethodFilter
。如果使用的是 Spring Boot,通常情况下这个过滤器是默认启用的。如果没有自动配置,可以手动添加它到配置类中:
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<>(new HiddenHttpMethodFilter());
registrationBean.setOrder(0); // 设置过滤器的优先级
return registrationBean;
}
}
控制器代码
接下来,在控制器中处理这个请求:
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/resources")
public class ResourceController {
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteResource(@PathVariable String id) {
// 执行删除操作...
return ResponseEntity.ok("Resource deleted");
}
}
在这个控制器方法中,定义了一个处理 DELETE 请求的方法,当用户通过上面的表单提交后,HiddenHttpMethodFilter
会将 POST 请求转换为 DELETE 请求,然后由这个方法来处理。
这种方式提供了一种简便的方法来使用非 GET/POST 的 HTTP 方法,而不需要依赖于 AJAX 调用或其他客户端技术。不过,随着前后端分离的趋势和 RESTful API 的流行,直接通过 JavaScript 发起各种类型的 HTTP 请求变得越来越常见。即便如此,HiddenHttpMethodFilter
对于传统的基于表单的应用仍然非常有用。