Spring MVC – URI Templates

  在spring mvc中通过url路径来访问控制器中的方法,可以在用@RequestMapping注解的路径中使用URI模板。使用@PathVariable注解来指明方法中的参数应该对应URI模板中的变量,如下例子:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  model.addAttribute("owner", owner);  
  return "displayOwner"; 
}

  URI模板”/owners/{ownerId}”指定了变量名为ownerId。当方法被请求的时候ownerId的值会被赋值为请求的URI,比如一个请求为/owners/fred,那么方法中的ownerId参数会赋值为fred。必须保证参数名和URI模板变量名一致才能自动赋值,想自定义参数变量需要在@PathVariable注解中加入参数,如下:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
  // implementation omitted
}

  当然,也可以使用多个@PathVariable来绑定多个URI模板变量,如下:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)
public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  Owner owner = ownerService.findOwner(ownderId);  
  Pet pet = owner.getPet(petId);  
  model.addAttribute("pet", pet);  
  return "displayPet"; 
}

  下面的代码展示使用变量作为相对路径,当请求为/owners/42/pets/21,会调用findPet()方法。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
  @RequestMapping("/pets/{petId}")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
    // implementation omitted
  }
}

  @PathVariable和方法中的参数可以是任何简单数据类型,例如:int,long,Date,等等。spring会自动转换,如果不匹配则抛出TypeMismatchException。

  原文:link

本文链接地址:https://dorole.com/415/

来自:Dorole's Blog

发布者

Steve

编程/摄影

《Spring MVC – URI Templates》上有1条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: