我正在尝试为处理 COPY HTTP 方法的资源创建自定义 Spring MVC Controller 。
@RequestMapping仅接受以下 RequestMethod值:GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS 和 TRACE。
在 Spring MVC Controller 中是否有任何推荐的处理自定义 HTTP 方法的方法?
最佳答案
Servlet specification仅允许 GET
、HEAD
、POST
、PUT
、DELETE
、OPTIONS
或 TRACE
HTTP 方法。这可以在 Apache Tomcat 中看到 implementation of the Servlet API .
这反射(reflect)在 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
关于java - Spring MVC 中的自定义 HTTP 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33302397/