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.
@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.
Look at the below code example. I have posted only the controller class with the @PathVariable configuration.
package aid.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; @Controller 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"; } @RequestMapping(value="/aid/{regexp1:[a-z-]+}", 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.