URI Template = URI (URL ) + one or more variable.
URI Template is a URI with one or more variable.
For example : http://localhost:8080/login/{usename}
here URI is http://localhost:8080/login/ and variable is {username}
If we assign the variable(username) the value sriram, the URI Template will be: http://localhost:8080/login/sriram
In spring 3, if you want to access parts of a request URL, use URI templates in the @RequestMapping path value.
In Controller method we need to use @PathVariable (method parameter annotation) to indicate that a method parameter should be bound to the value of a URI template variable.
Following code shows, how to use @PathVariable in controller
@RequestMapping( value="/login/{usename}" method = RequestMethod.GET) public String loginForm(@PathVariable String usename, ModelMap model) { System.out.println("user name" +username); LoginForm loginForm = new LoginForm(); model.addAttribute("loginForm",loginForm); return "loginForm"; }
When a request comes in for /login/sriram, the value sriram is bound to the method parameter String username.
We can also bind the URI template variable with method parameters as below
@RequestMapping( value="/login/{usename}" method = RequestMethod.GET) public String loginForm(@PathVariable("username") String userId, ModelMap model) { System.out.println("user name" +userId); LoginForm loginForm = new LoginForm(); model.addAttribute("loginForm",loginForm); return "loginForm"; }
Binding more than one variable
@RequestMapping( value="/login/{usename}/employee/{employeeId}" method = RequestMethod.GET) public String loginForm(@PathVariable("username") String userId, @PathVariable("employeeId") String employeeId, ModelMap model) { System.out.println("user name" +userId); System.out.println("employee Id" +employeeId); LoginForm loginForm = new LoginForm(); model.addAttribute("loginForm",loginForm); return "employeeLoginForm"; }
No comments:
Post a Comment