【问题标题】:Spring MVC Request method 'PATCH' not supported不支持 Spring MVC 请求方法“PATCH”
【发布时间】:2026-01-02 07:15:01
【问题描述】:

在 Spring MVC/Boot 中是否默认不启用 HTTP PATCH?我收到 ff 错误:

org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PATCH' not supported
        at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:213)

对于我的控制器:

@PatchMapping("/id")
public ResourceResponse updateById(@PathVariable Long id, ServletServerHttpRequest request) {

我的配置如下:

.antMatchers(HttpMethod.PATCH, "/products/**").hasRole("MANAGER")
...
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));

查了SpringFrameworkServlet.java的源码,PATCH有什么特别之处:

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
    if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
        processRequest(request, response);
    }
    else {
        super.service(request, response);
    }
}

我已经用谷歌搜索了,但找不到任何可以帮助解决我的问题的东西。

谢谢。

【问题讨论】:

  • 我尝试了一个演示 Spring Boot 应用程序,补丁按预期工作。您的代码中有一个不相关的问题...您在 updateById 方法中使用了 ''@PathVariable("id")" ,但 URI 中没有 pathVariable 占位符。
  • 哦。接得好!我肯定认为这就是原因。我错过了{}。谢谢。
  • 如果这样可以解决您的问题。我应该弹出它作为答案吗?
  • 当然,我会接受它作为答案。

标签: java spring-boot spring-mvc http-patch


【解决方案1】:

我尝试了一个演示 Spring Boot 应用程序,补丁按预期工作。

您的代码中有一个不相关的问题...您在 updateById 方法中使用 @PathVariable("id"),但 URI 中没有 pathVariable 占位符。

【讨论】:

    【解决方案2】:

    标准的 HTTP 客户端不支持 PATCH 请求。

    您可以将 apache HTTP 客户端添加到您的项目中。如果在类路径中找到它应该由 spring boot 自动添加。

    https://hc.apache.org/

    【讨论】:

      【解决方案3】:

      我确实解决了问题,就我而言,我犯了一个错误,我写道 @PatchMapping(params = "/{id}", consumes = "application/json")

      而不是: @PatchMapping(path = "/{id}", consumes = "application/json")

      【讨论】: