Software Developers
Showing results for 
Search instead for 
Do you mean 

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

amirkibbar on ‎04-22-2013 10:47 PM

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

0 Kudos
About the Author

amirkibbar

Events
Aug 29 - Sep 1
Boston, MA
HPE Big Data Conference 2016
Attend HPE’s Big Data Conference on August 29 - September 1, 2016 to learn from peers in every industry and hear from Big Data experts and thought lea...
Read more
Sep 13-16
National Harbor, MD
HPE Protect 2016
Protect 2016 is our annual conference on September 13 - 16, 2016, and is the place to meet the world’s top information security talent, discuss new pr...
Read more
View all