spring-bootspring-restcontrollerspring-restspring-webhttp-method

spring REST RequestMethod how to Map a http LOCK and UNLOCK RequestMapping?


seems that this is the same as Custom HTTP Methods in Spring MVC

I need to implement a call with http method LOCK and UNLOCK.

currently spring's requestMethod only supports

public enum RequestMethod {

    GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

}

how can I implement a @RestController method that is called if the spring app is called with LOCK and UNLOCK http directives?


Solution

  • You can do it using supported method ( GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE) call. Here is the way to call post method internally:

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurationSupport {
    
        @Override
        @Bean
        public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
    
            final RequestMappingHandlerAdapter requestMappingHandlerAdapter = super.requestMappingHandlerAdapter();
            requestMappingHandlerAdapter.setSupportedMethods(
                "LOCK", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"
            ); //here supported method
    
            return requestMappingHandlerAdapter;
        }
    
        @Bean
        DispatcherServlet dispatcherServlet() {
            return new CustomHttpMethods();
        }
    }
    

    Custom method handler class. Here call post method internally:

    public class CustomHttpMethods extends DispatcherServlet {
    
        @Override
        protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    
            if ("LOCK".equals(request.getMethod())) {
                super.doPost(request, response);
            } else {
                super.service(request, response);
            }
        }
    
    }
    

    Now you do requestmapping below way:

    @RequestMapping(value = "/custom")
    ResponseEntity customHttpMethod(){
        return ResponseEntity.ok().build();
    }