URI Pattern Binding

URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI.

For example http://localhost:8080/STMavenSpringMVC/PathVariable/get/{id} contains variable id. Assigning the value 99 to the variable makes url http://localhost:8080/STMavenSpringMVC/PathVariable/get/99.

You can use the @PathVariable to bind method parameters to the value of a URI template variable.

Here is the example of controller PathVariablesCtl that binds path variables:

@Controller

@RequestMapping(value = "/PathVariable")

public class PathVariablesCtl {

//Binds URI path variable id to method parameter id.

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)

public String singlePath(@PathVariable int id, Model model) {

String message = "You have sent id : " + id + " as part of URL";

model.addAttribute("message", message);

return "PathVariableView";

}

//Binds URI path variables deptId and empId to respective method parameters.

@RequestMapping(value = "/get/{deptId}/{empId}", method = RequestMethod.GET)

public String multiplePath(@PathVariable int deptId, @PathVariable int empId, Model model) {

String message = "You have sent Department ID : " + deptId

+ " and Employee ID " + empId + " as part of URL";

model.addAttribute("message", message);

return "PathVariableView";

}

}

The URI Template " /get/{id}" specifies the variable name "id". When the controller handles this request, the value of "id" is set to the value found in the appropriate part of the URI. For example, when a request comes in for /get/99, the value of "id" is 99. Similarly when request comes in for \get\11\203, the value of deptId is 11 and empId is 203.

When method argument name is different then URI Template variable then you can have to pass URI template variable name in @PathVariable annotation. In this example code URI Template variable deptId is bond with dId method argument.

@RequestMapping(value = "/get/{deptId}/{empId}", method = RequestMethod.GET)

public String multiplePath(@PathVariable("deptId") int dId, @PathVariable int empId, Model model) {

A method can have any number of @PathVariable annotations. A @PathVariable argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do so. You can also register support for parsing additional data types using custom WebDataBinder.