33

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)
nabster
  • 1,561
  • 2
  • 20
  • 32
zmanc
  • 5,201
  • 12
  • 45
  • 90

2 Answers2

51

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) {
    // ...
  }
}
kryger
  • 12,906
  • 8
  • 44
  • 65
sam
  • 3,441
  • 2
  • 33
  • 42
  • Thank you for the response. May I add another related question? Is it allowed to have other(s) variable(s) after a variable having a regex allowing many values, like /{name:.+}/bla/{othervariable}/blo/{anotherone} In this example, what will happen if there is / inside the name ? – NicoESIEA Feb 09 '23 at 09:57
2

You should use:

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

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

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
  • 4
    I edited the answer to remove the reference to the "solution", as such statement belongs in a comment, not in an answer. However, it would be good if you would explain in your answer (edit it) what the provided code does with respect to the question. – trincot Nov 30 '15 at 16:12