SpringMVC中 @RequestParam 与 @PathVariable 区别

发布时间 2023-12-04 11:42:29作者: Kael'thas

两者都是用来修饰形参
两者都是用来绑定访问路径的参数名、形参名称
两者接收URL方式不同

@RequestParam

http://www.example.com/pets?petId=3

@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {

    // ...

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

@PathVariable

http://www.example.com/owners/11

@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"; 
}