---
title: "Spring学习笔记之@ModelAttribute"
author: "PrisonBreak"
date: "2015-01-24T22:23:42Z"
tags: []
categories: ["编程语言"]
slug: "spring-modelattribute"
draft: false
lastmod: "2015-01-24T22:23:42Z"
id: 2179337
url: "https://prisonbreak.iteye.com/blog/2179337"
---

### 使用`@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();
		}
	}

}
```