form表单提交RestFul

HTML表单

html表单提交只有两种够选项: get和post

如何使用RestFul风格?

方法

添加一个隐藏的参数_method

1
<input type="hidden" name="_method" value="PUT">

This can be done automatically in frameworks through the HTML creation helper method.

在常见的后台框架中,都会有转换的支持

比如在SpringBoot中

  • 有一个核心Filter: hiddenHttpMethoddFilter
    • 用法: 表单method=post, 隐藏域_method=put
    • 原理: 请求是否正常,并且是POST
      • 如果是,获取_method的值,转换为大写
      • 兼容PUT,DELETE,PATCH
      • requestWrapper(重写了getMethod方法,返回的是传入的值)包装原生request
      • 过滤器链放行的是requestWrapper,以后的方法调用getMethod是调用的requestWrapper的
  • 配置spring.mvc.hiddenmethod.filter的enabled为true即可生效

示例:

1
2
3
4
<form action="/user" method="post">
<input name="_method" type="hidden" value="PUT"/>
<input value="REST-PUT" type="submit"/>
</form>