Spring MVC Request mapping, can this be dynamic/configurable?

前端 未结 5 752
慢半拍i
慢半拍i 2021-02-19 06:37

With Spring MVC, I know how you set the RequestMapping in every controller and method/action.

But what if I wanted this to be configurable, so for example I

相关标签:
5条回答
  • 2021-02-19 06:59

    Would this sort of URL mapping work for you?

    www.example.com/blog/1/
    www.example.com/blog/2/
    

    If yes, then that's easy: Spring 3 supports path variables: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestmapping-advanced

    Alternatively, you can create a generic request mapping and your own sub-dispatcher that reads a config file, but I think that's probably more work than it's worth.

    0 讨论(0)
  • 2021-02-19 07:08

    Truly changing the request mappings at runtime might be hard (and not really recommended, since small errors can easily occur). If you still wish to do it, perhaps JRebel, and more specificly LiveRebel can be interesting for live redeployment of code and configuration.

    Otherwise, like other posts suggested, RequestMappings supports wildcards, the limits of this should be clear after a quick read of the official documentation.

    0 讨论(0)
  • 2021-02-19 07:10

    Also another solution might be to create a custom annotation that holds the already defined path on the @RequestMapping and also the new one to apply, let's say @ApiRestController.

    Then, before the Spring context loads, the @Controller classes can be changed to have their annotation values changed at runtime by the new one (with the desired path). By doing this, Spring will load the enhanced request mapping and not the default one.

    Created a small project to exemplify this for someone that needs this in the future https://gitlab.com/jdiasamaro/spring-api-rest-controllers.

    Hope it helps. Cheers.

    0 讨论(0)
  • 2021-02-19 07:12

    doesn't this work? @RequestMapping("/helloWorld*")

    0 讨论(0)
  • 2021-02-19 07:15

    Try using with @RequestMapping wild cards as below:

    @RequestMapping(value="/article_section*/"}
    public void getArticle(....){
    //TODO implementation
    }
    
    @RequestMapping(value="/blog*/"}
    public void getBlog(....){
    //TODO implementation
    }
    

    Hope this helps!!!

    0 讨论(0)
提交回复
热议问题