Is it possible to dynamically set RequestMappings in Spring MVC?

后端 未结 6 1804
心在旅途
心在旅途 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:31

    Please look at my solution. It doesn't create dynamic @RequestMapping in your code, but provides a HandlerMapping and Controller that handles all request. If you run that application, you will get hello world message in json.

    Application class:

    @SpringBootApplication
    public class Application {
      public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
      }
    
      @Bean
      public MyCustomHandler myCustomHandler(MyCustomController myCustomController) {
        MyCustomHandler myCustomHandler = new MyCustomHandler(myCustomController);
        myCustomHandler.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return myCustomHandler;
      }
    }
    

    MyCustomController

    @Component
    public class MyCustomController extends AbstractController {
    
      @Override
      protected ModelAndView handleRequestInternal(HttpServletRequest request,
          HttpServletResponse response) throws Exception {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().println("{\"hello\":\"world\"}");
        return null;
      }
    }
    

    MyCustomHandler

    public class MyCustomHandler extends AbstractHandlerMapping {
    
      private MyCustomController myCustomController;
    
      public MyCustomHandler(MyCustomController myCustomController) {
        this.myCustomController = myCustomController;
      }
    
      @Override
      protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
        return myCustomController;
      }
    }
    

    https://github.com/nowszy94/spring-mvc-dynamic-controller

提交回复
热议问题