在 HTML 表单仅支持 GET/POST 时,如何通过 _method 参数让 Struts 识别 PUT 请求?

解读

国内主流浏览器只把 form 的 method 属性解析为 GET 或 POST,PUT、DELETE 等动词无法直接发出。
Struts2 为了兼容 REST 风格,在 struts2-rest-plugin 里内置了 HttpMethodInterceptor,它会优先读取请求参数 _method 的值,再与 ActionMapper 配合,把该值写入 ActionMapping 的 HTTP 方法字段,从而“伪装”成一次 PUT 请求。
因此,前端只要保证 _method=PUT 随请求一起到达后端,Struts 就能在拦截器栈里完成识别,无需改动核心过滤器。

知识点

  1. struts2-rest-plugin 的 HttpMethodInterceptor 默认拦截参数名 _method,大小写敏感。
  2. 该拦截器在 restStack 拦截器栈中已声明,若自定义栈需手动加入。
  3. 仅对 POST 请求生效,GET 带 _method 会被忽略,防止 CSRF 篡改。
  4. 常量 struts.mapper.methodParameter 可修改参数名,默认值 _method。
  5. 若使用 Convention 插件 零配置,需保证 Action 类或其名以 Controller 结尾,才能落入 rest 命名空间并触发 REST 映射。

答案

第一步:引入依赖

<dependency>
  <groupId>org.apache.struts</groupId>
  <artifactId>struts2-rest-plugin</artifactId>
  <version>2.5.30</version>
</dependency>

第二步:在 struts.xml 中启用 rest 拦截器栈

<package name="rest" namespace="/api" extends="rest-default">
    <action name="user/*" class="com.xxx.UserController">
        <interceptor-ref name="restStack"/>
        <result type="json"/>
    </action>
</package>

第三步:表单端构造 POST 请求并追加隐藏字段

<form action="${pageContext.request.contextPath}/api/user/123" method="post">
    <input type="hidden" name="_method" value="PUT"/>
    <input type="text" name="userName" value="张三"/>
    <button type="submit">更新</button>
</form>

第四步:后端 Controller 使用 REST 注解

public class UserController implements ModelDriven<User> {
    public HttpHeaders update() {
        // 此时 Struts 已把 _method=PUT 识别为 PUT 请求
        service.update(model);
        return new DefaultHttpHeaders("update").setStatus(204);
    }
}

通过以上四步,_method=PUT 被 HttpMethodInterceptor 捕获,ActionMapping 的 HTTP 方法被改写,Struts 正常进入 update 方法,完成一次“伪 PUT”更新操作。

拓展思考

  1. 国内很多银行、政务内网仍使用 IE9 以下内核,无法发 XMLHttpRequest 的 PUT,因此 _method 伪装 是生产环境最稳妥的方案。
  2. 若项目同时暴露给移动端,建议把 _method 参数放在 HTTP Header X-HTTP-Method-Override 中,后端重写 HttpMethodInterceptor 的 getMethodParameter,实现“参数+Header”双通道兼容。
  3. 高并发场景下,rest-plugin 会把 ActionMapping 缓存在 org.apache.struts2.rest.RestActionMapper 的 ConcurrentHashMap,注意设置 struts.rest.mappingCacheSize 防止内存泄漏。
  4. 升级到 Struts 6 之后,rest-plugin 被合并进 struts-core,但 _method 机制保持不变,迁移时只需把 rest-default 换成 struts-default 并保留 restStack 即可。