Spring MVC 确实可以处理来自 POST 和 GET 以外的 HTML 表单请求,但有一些限制和注意事项需要了解。
HTML 表单标准只正式支持 GET 和 POST 方法。这是由 HTML 规范决定的,<form>
元素的 method
属性只接受这两个值。
虽然 HTML 表单本身不支持,但 Spring MVC 提供了几种方式来处理其他 HTTP 方法:
<form action="/process" method="post">
<input type="hidden" name="_method" value="PUT">
<!-- 其他表单字段 -->
<button type="submit">提交</button>
</form>
在 Spring Boot 应用中,需要启用 HiddenHttpMethodFilter
(默认已启用):
@Configuration
public class WebConfig {
// Spring Boot 2.x 自动配置了这个过滤器
// 如果需要手动配置:
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new HiddenHttpMethodFilter();
}
}
// 使用 Fetch API
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
fetch(this.action, {
method: 'PUT', // 或 DELETE 等
body: new FormData(this)
}).then(response => {
// 处理响应
});
});
$.ajax({
url: '/resource/123',
type: 'PUT',
data: $('#myForm').serialize(),
success: function(result) {
// 处理结果
}
});
@RestController
@RequestMapping("/resource")
public class ResourceController {
@PutMapping("/{id}")
public ResponseEntity<?> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
// 处理 PUT 请求
return ResponseEntity.ok().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteResource(@PathVariable Long id) {
// 处理 DELETE 请求
return ResponseEntity.noContent().build();
}
}
enctype
属性正确设置(如 multipart/form-data
用于文件上传)问题:PUT/DELETE 请求返回 405 方法不允许
原因:服务器未正确配置或过滤器未启用
解决:确保 HiddenHttpMethodFilter
已配置,或直接使用 AJAX 请求
问题:CSRF 令牌缺失 原因:非 GET 请求需要 CSRF 保护 解决:在表单中添加 CSRF 令牌:
<input type="hidden" name="_csrf" value="${_csrf.token}"/>
Spring MVC 提供了灵活的方式来处理各种 HTTP 方法,虽然 HTML 表单本身有限制,但通过上述技术可以完整支持 RESTful 风格的应用开发。
没有搜到相关的文章