1 Reply
In spring mvc, a URL path is used to access the methods in the controller, and the URI template is available in the path with the @requestmapping annotation. Use the @pathvariable annotation to indicate that the parameters in the method should correspond to the variables in the URI template, as follows: View source print?
1 |
@RequestMapping (value= "/owners/{ownerid}", Method=requestmethod.get) |
2 |
public string Findowner (@PathVariable string ownerid, model model) { |
3 |
Owner owner = ownerservice.findowner (ownerid); |
4 |
Model.addattribute ("owner", owner); |
The URI template "/owners/{ownerid}" specifies a variable named ownerid. When the method is requested, the value of the ownerid is assigned to the requested URI, such as a request for/owners/fred, then the ownerID parameter in the method is assigned to Fred. You must ensure that the parameter name and the URI template variable name are consistent to automatically assign a value, and you want to customize the parameter variable to include the parameter in the @pathvariable note, as follows: View source print?
1 |
@RequestMapping (value= "/owners/{ownerid}", Method=requestmethod.get) |
2 |
public string Findowner (@PathVariable ("ownerID") string Theowner, model model) { |
Of course, you can also use multiple @pathvariable to bind multiple URI template variables, as follows: View source print?
1 |
@RequestMapping (value= "/owners/{ownerid}/pets/{petid}", Method=requestmethod.get) |
2 |
public string Findpet (@PathVariable string ownerid, @PathVariable string petid, model model) { |
3 |
Owner owner = ownerservice.findowner (Ownderid); |
4 |
Pet pet = Owner.getpet (Petid); |
5 |
Model.addattribute ("Pet", pet); |
The following code shows the use of a variable as a relative path, and the Findpet () method is invoked when the request is/OWNERS/42/PETS/21. View Source print?
2 |
@RequestMapping ("/owners/{ownerid}") |
3 |
public class Relativepathuritemplatecontroller { |
4 |
@RequestMapping ("/pets/{petid}") |
5 |
public void Findpet (@PathVariable string ownerid, @PathVariable string petid, model model) { |
The parameters in @PathVariable and methods can be any simple data type, for example: Int,long,date, and so on. Spring automatically converts and throws a typemismatchexception if it does not match.