使用@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();
}
}
}
本文深入探讨了@ModelAttribute注解在Spring MVC控制器中的两种主要用途:作为方法参数实现表单数据与方法的连接,以及在方法级别为模型提供预填充的数据。通过示例代码展示如何有效利用这一特性进行表单验证与数据处理。
1334

被折叠的 条评论
为什么被折叠?



