Regex in spring controller

2019-01-23 03:59发布

问题:

I am trying to build a request filter that will only get used if it matches a pattern of the letter e, then a number. However I cannot seem to get it to work. I keep getting 400 errors every time I try something with regex.

If I just use the following it "works" but also captures mappings that do not have numbers which I don't want.

@RequestMapping(value = "e{number}",
            method = RequestMethod.GET)

I have tried the following combinations.

@RequestMapping(value = "e{number}",
            params = "number:\\d+",
            method = RequestMethod.GET)

@RequestMapping(value = "e{number:\d+}",
            method = RequestMethod.GET)

@RequestMapping(value = "/e{^\\+?\\d+\$}",
            method = RequestMethod.GET)

@RequestMapping(value = "/{^\\e+?\\d+\$}",
            method = RequestMethod.GET)

回答1:

According to the documentation, you have to use something like {varName:regex}. There's even an example :

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
  public void handle(@PathVariable String version, @PathVariable String extension) {
    // ...
  }
}


回答2:

You should use:

 @RequestMapping("/e{number:\\d+})

Notice the "escaped slash" before the \d digit specifier.