Search code examples
javaspringspring-bootrequest-mapping

spring boot requestmapping regex


I have a need to have a single function in a controller map to multiple urls differing by only a few characters. url1: npp/v0/membership url2: npp/hcl/v2/membership

  1. Is there a way to only allow these 2 strings?
  2. What if I want to allow anything pattern?

Thanks.


Solution

  • Just allowing the two strings would mean you want to use the "path" attribute of the @RequestMapping as it allows an array of Strings.

    @RequestMapping(path = {"/npp/v0/membership", "/npp/hcl/v2/membership"})
    public void membership() { }
    

    If you want to wildcard you just need to use Ant expressions:

    @RequestMapping(path = "/npp/**")
    public void npp() { }
    

    If you want the details of the path that was used you would need to look at the HttpServletRequest object that you can have passed into the method.