在spring mvc中通过url路径来访问控制器中的方法,可以在用@RequestMapping注解的路径中使用URI模板。使用@PathVariable注解来指明方法中的参数应该对应URI模板中的变量,如下例子:
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); |
5 | return "displayOwner"; |
6 | } |
URI模板”/owners/{ownerId}”指定了变量名为ownerId。当方法被请求的时候ownerId的值会被赋值为请求的URI,比如一个请求为/owners/fred,那么方法中的ownerId参数会赋值为fred。必须保证参数名和URI模板变量名一致才能自动赋值,想自定义参数变量需要在@PathVariable注解中加入参数,如下:
1 | @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) |
2 | public String findOwner(@PathVariable("ownerId") String theOwner, Model model) { |
3 | // implementation omitted |
4 | } |
当然,也可以使用多个@PathVariable来绑定多个URI模板变量,如下:
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); |
6 | return "displayPet"; |
7 | } |
下面的代码展示使用变量作为相对路径,当请求为/owners/42/pets/21,会调用findPet()方法。
1 | @Controller |
2 | @RequestMapping("/owners/{ownerId}") |
3 | public class RelativePathUriTemplateController { |
4 | @RequestMapping("/pets/{petId}") |
5 | public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { |
6 | // implementation omitted |
7 | } |
8 | } |
@PathVariable和方法中的参数可以是任何简单数据类型,例如:int,long,Date,等等。spring会自动转换,如果不匹配则抛出TypeMismatchException。
本文介绍SpringMVC框架中如何使用URI模板和@PathVariable注解来处理URL路径参数,包括基本用法、参数绑定及相对路径的设置。
1699






