---
title: "@ModelAttribute注解的使用"
author: "raymond.chen"
date: "2019-11-06T20:10:37Z"
tags: []
categories: ["编程语言"]
slug: "modelattribute"
draft: false
lastmod: "2019-11-06T20:10:37Z"
id: 2509666
url: "https://chenjumin.iteye.com/blog/2509666"
---

@ModelAttribute注解用于将请求参数绑定到Model对象。

在Controller类所有方法执行前，先调用此@ModelAttribute方法，可用于注解方法和方法参数。

 

@ModelAttribute注释方法

```
//@ModelAttribute注释void返回值的方法
public void populateModel(@RequestParam String attrValue, Model model) { 
	model.addAttribute("attributeName", attrValue); 
} 

//@ModelAttribute注释返回具体类的方法
//model属性的名称没有指定，它由返回类型隐含表示，范例中model属性的名称是account
@ModelAttribute 
public Account addAccount(@RequestParam String number) { 
	return accountManager.findAccount(number); 
} 

//@ModelAttribute(value="")注释返回具体类的方法
//使用value属性来指定model属性的名称，model属性对象就是方法的返回值
@ModelAttribute("attributeName") 
public String addAccount(@RequestParam String attrValue) { 
	return attrValue; 
} 
```

 

@ModelAttribute注释一个方法的参数

```
@RequestMapping(value = "/helloWorld") 
public String helloWorld(@ModelAttribute("user") User user) { 
	user.setUserName("jizhou"); 
	return "helloWorld"; 
} 
```