In Spring MVC you can use the @PathVariable on a method to bind it to the value of a URI template variable. Lets see various Spring MVC Path Variable Example.
1. Simple Path Variable
1 2 3 4 5 6 |
@RequestMapping(value = "/employee/{empName}") public String employeeName(@PathVariable String empName) { // Implement your logic here } |
The URI template
/employee/{empName} specifies the variable
empName. When a request to the Controller with this URI comes, the controller assigns value to the variable empName based on the value found in the URI
example :
/employee/Steve, the value of empName will be Steve
Alternatively if you want to assign the value of your path variable to some other variable that is not mentioned in the URI, then you need to give that name in the PathVariable annotation.
1 2 3 4 5 |
@RequestMapping(value = "/employee/{empName}") public String employeeName(@PathVariable("empName") String newName) { // Implement your logic here } |
2. Using Multiple Path Variable
You can use any number of path variables in your URL and at any location.
1 2 3 4 5 6 |
@RequestMapping(value = "/employee/{empName}/dept/{deptName}") public String employeeName(@PathVariable String empName, @PathVariable String deptName) { // Implement your logic here } |
In this case the Controller method will be called by URI such as /employee/Steve/dept/Sales
3. Using Path Variable as a Map
When you use a @PathVariable on a Map<String,String> , the map will be populated with all the path variables that are mentioned in the URL
1 2 3 4 5 6 |
@RequestMapping(value = "/employee/{empName}/{deptName}/{salary}/{age}") public String employeeName(@PathVariable Map<String, String> empMap) { // Implement your logic here } |
So in here if we give a URL as /employee/Steve/Sales/3500/25 , then the Map of Path variables will contain the following values
1 2 3 4 |
empName = Steve deptName = Sales salary = 3500 age = 25 |
4. Using Regular expression in Path Variables
Regular expression can be used in the path variables with the syntax –
{variableName:regex}
Suppose you have a URL as
/operatingsystem/android-marshmallow-6.0.1 , using regex you can get the os, name and its version in different variables.
1 2 3 4 5 6 7 |
@RequestMapping("/operatingsystem/{os:[a-z-]+}-{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}") public String pathVariableRegEx(@PathVariable String os, @PathVariable String name, @PathVariable String version) { // Implement your logic here } |