Spring MVC中的自定义HTTP方法

wo.*_*uch 7 java spring-mvc spring-data-rest

我正在尝试为处理COPY HTTP方法的资源创建自定义Spring MVC Controller.

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

在Spring MVC Controller中是否有任何推荐的处理自定义HTTP方法的方法?

Zor*_*art 5

Servlet规范只允许GETHEADPOSTPUTDELETEOPTIONSTRACEHTTP方法。这可以在 Servlet API的 Apache Tomcat实现中看到。

这反映在 Spring API 的RequestMethod枚举中

您可以通过实现自己的DispatcherServlet覆盖service方法以允许COPYHTTP 方法来绕过这些方法 - 将其更改为 POST 方法,并自定义RequestMappingHandlerAdapterbean 以允许它。

像这样,使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

curl -v -X COPY http://localhost:8080/method
Run Code Online (Sandbox Code Playgroud)