【问题标题】:Custom HTTP Methods in Spring MVCSpring MVC 中的自定义 HTTP 方法
【发布时间】:2016-01-22 23:50:33
【问题描述】:

我正在尝试为处理 COPY HTTP 方法的资源创建自定义 Spring MVC 控制器。

@RequestMapping 仅接受以下 RequestMethod 值:GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS 和 TRACE。

在 Spring MVC Controller 中处理自定义 HTTP 方法有什么推荐的方法吗?

【问题讨论】:

标签: java spring-mvc spring-data-rest


【解决方案1】:

Servlet specification 仅允许 GETHEADPOSTPUTDELETEOPTIONSTRACE HTTP 方法。这可以在 Apache Tomcat implementation of the Servlet API 中看到。

这反映在 Spring API 的 RequestMethod enumeration 中。

您可以通过实现自己的 DispatcherServlet 覆盖 service 方法以允许 COPY HTTP 方法来欺骗这些方法 - 将其更改为 POST 方法,并自定义 RequestMappingHandlerAdapter bean 以允许它。

类似这样的东西,使用 spring-boot:

@Controller
@EnableAutoConfiguration
@Configuration
public class HttpMethods extends WebMvcConfigurationSupport {

    public static class CopyMethodDispatcher extends DispatcherServlet {
        private static final long serialVersionUID = 1L;

        @Override
        protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
            if ("COPY".equals(request.getMethod())) {
                super.doPost(request, response);
            }
            else {
                super.service(request, response);
            }
        }
    }

    public static void main(final String[] args) throws Exception {
        SpringApplication.run(HttpMethods.class, args);
    }

    @RequestMapping("/method")
    @ResponseBody
    public String customMethod(final HttpServletRequest request) {
        return request.getMethod();
    }

    @Override
    @Bean
    public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        final RequestMappingHandlerAdapter requestMappingHandlerAdapter = super.requestMappingHandlerAdapter();
        requestMappingHandlerAdapter.setSupportedMethods("COPY", "POST", "GET"); // add all methods your controllers need to support

        return requestMappingHandlerAdapter;
    }

    @Bean
    DispatcherServlet dispatcherServlet() {
        return new CopyMethodDispatcher();
    }
}

现在您可以使用COPY HTTP 方法调用/method 端点。使用 curl 这将是:

curl -v -X COPY http://localhost:8080/method

【讨论】:

  • 这在最新的 Spring Boot Starter 2.2.5 中不起作用
猜你喜欢
  • 2017-08-12
  • 2016-01-27
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2014-09-13
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多