使用@ModelAttribute提供一個從模型到數據的鏈接
@ModelAttribute在控制器中有兩種使用場景。 當作爲一個方法參數時,@ModelAttribute用於映射一個模型屬性到特定的註解的方法參數(見下面的processSubmit()方法)。 這是控制器獲得持有表單數據的對象引用的方法。另外,這個參數也可以被聲明爲特定類型的表單支持對象,而不是一般的java.lang.Object,這就增加了類型安全性。
@ModelAttribute也用於在方法級別爲模型提供引用數據(見下面的populatePetTypes()方法)。 在這種用法中,方法編寫可以包含與上面描述的@RequestMapping註解相同的類型。
注意:使用@ModelAttribute註解的方法將會在選定的使用@RequestMapping註解的方法之前執行。 它們有效的使用特定的屬性預先填充隱含的模型,這些屬性常常來自一個數據庫。 這樣一個屬性也就可以通過在選定的方法中使用@ModelAttribute註解的句柄方法參數來訪問了,潛在的可以應用綁定和驗證。
下面的代碼片段展示了此註解的這兩種用法:
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result,
SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}
else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
}
}
}