Using Regular Expressions to Evaluate Path Variables in a Spring MVC controller

Sometime you may want to process the URI in the request and assign values to several path variables instead of a single one. This can easily be achieved with regular expressions on the URI itself within the @RequestMapping.

 

The syntax is {varName:regex} for the parsed URI path variable. For example suppose we want to provide an HTTP GET over this URI: /jars/log4j-1.2.16.jar, but we want to allow any jar name, version and extension with the format name-version.extension and we also want to get each of these path variables in a separate argument in our controller handler method. We can do it this way:

 

 

@Controller
public final class MyController {
     @RequestMethod("/jars/{artifact:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
     public void handle(@PathVariable String artifact, @PathVariable String version, @PathVariable String extension) {
          ...
     }
}

 Simple and useful.

 

Post author: Amir Kibbar

Leave a Comment

We encourage you to share your comments on this post. Comments are moderated and will be reviewed
and posted as promptly as possible during regular business hours

To ensure your comment is published, be sure to follow the Community Guidelines.

Be sure to enter a unique name. You can't reuse a name that's already in use.
Be sure to enter a unique email address. You can't reuse an email address that's already in use.
Type the characters you see in the picture above.Type the words you hear.
Search
About the Author


Follow Us
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation