@PathVariable – URI Template Patterns in Spring MVC

This tutorial explains how to customize / template pattern on  request URI for Spring MVC web application. @RequestMapping annotation used for defining the request URL for the class level and method levels. It is generic annotation where developer can configure the relative paths inside application context. However, it doesn’t offer flexible URI patterns on its own. We have to use @PathVariable for accepting the customized or more dynamic parameters in the request paths. You can configure the complete path inside @RequestMapping with the placeholders for the dynamic URIs.

Look at the below code example. I have posted only the controller class with the @PathVariable configuration. If you are looking for the complete example for Spring MVC application, then read example 1 and example 2. If you have any questions, please write it in the comments section.

package javabeat.net;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class TestController {
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
     public String getLogin(@PathVariable("userId") String userId,
         @PathVariable("roleId") String roleId){
         System.out.println("User Id : " + userId);
         System.out.println("Role Id : " + roleId);
         return "hello";
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)
     public String getProduct(@PathVariable("productId") String productId){
           System.out.println("Product Id : " + productId);
           return "hello";
           method = RequestMethod.GET)
     public String getRegExp(@PathVariable("regexp1") String regexp1){
           System.out.println("URI Part 1 : " + regexp1);
           return "hello";

  • @PathVariable is very useful for dynamic URIs.
  • There is no limit on the number of parameters used in a single method. You can use more than one dynamic parameter in a single method’s parameter.
  • This can be used with Map argument. Parameters will be populated to the Map object.
  • A @PathVariable argument can be of any simple type such as int, long, Date, etc.

Hope this helps to understand the use of PathVariable in your controller. If you find any issues, please write your comments. I will help you in understanding this example.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!