Is it possible to dynamically set RequestMappings in Spring MVC?

后端 未结 6 1827
心在旅途
心在旅途 2020-12-04 13:31

I\'ve been using Spring MVC for three months now. I was considering a good way to dynamically add RequestMapping. This comes from the necessity to put controller parts in a

6条回答
  •  没有蜡笔的小新
    2020-12-04 14:32

    Following construct configures and implements handler methods in a single class.

    It is a combination of dynamic and static mapping - all the MVC annotations can be used like @RequestParam, @PathVariable, @RequestBody, etc.

    @RestController annotation creates bean and adds @ResponseBody to every handler method.

    @RestController
    public class MyController {
    
        @Inject
        private RequestMappingHandlerMapping handlerMapping;
    
        /***
         * Register controller methods to various URLs.
         */
        @PostConstruct
        public void init() throws NoSuchMethodException {
    
            /**
             * When "GET /simpleHandler" is called, invoke, parametrizedHandler(String,
             * HttpServletRequest) method.
             */
            handlerMapping.registerMapping(
                    RequestMappingInfo.paths("/simpleHandler").methods(RequestMethod.GET)
                    .produces(MediaType.APPLICATION_JSON_VALUE).build(),
                    this,
                    // Method to be executed when above conditions apply, i.e.: when HTTP
                    // method and URL are called)
                    MyController.class.getDeclaredMethod("simpleHandler"));
    
            /**
             * When "GET /x/y/z/parametrizedHandler" is called invoke
             * parametrizedHandler(String, HttpServletRequest) method.
             */
            handlerMapping.registerMapping(
                    RequestMappingInfo.paths("/x/y/z/parametrizedHandler").methods(RequestMethod.GET)
                    .produces(MediaType.APPLICATION_JSON_VALUE).build(),
                    this,
                    // Method to be executed when above conditions apply, i.e.: when HTTP
                    // method and URL are called)
                    MyController.class.getDeclaredMethod("parametrizedHandler", String.class, HttpServletRequest.class));
        }
    
        // GET /simpleHandler
        public List simpleHandler() {
            return Arrays.asList("simpleHandler called");
        }
    
        // GET /x/y/z/parametrizedHandler
        public ResponseEntity> parametrizedHandler(
                @RequestParam(value = "param1", required = false) String param1,
                HttpServletRequest servletRequest) {
            return ResponseEntity.ok(Arrays.asList("parametrizedHandler called", param1));
        }
    }
    

提交回复
热议问题