Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in spring controller

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) 
like image 969
zmanc Avatar asked Aug 24 '13 19:08

zmanc


People also ask

What is @valid Annotation in spring boot?

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations.

Why do we use regex in Java?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.

What is @valid in Java?

The Java Bean Validation's @Valid constraint annotation makes sure that when an object is validated, the validation recurses to all fields that are annotated with @Valid . This makes it really easy to perform the usually complex task of validating entire object graphs.


1 Answers

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) {     // ...   } } 
like image 78
sam Avatar answered Sep 22 '22 21:09

sam