Spring MVC Path Variable Example

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

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.

2. Using Multiple Path Variable

You can use any number of path variables in your URL and at any location.

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

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

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. Spring Web Doc