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)

2 Answers 2

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) {
    // ...
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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 ?
2

You should use:

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

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.