能否请你动动手指,留下你的一键三连。
官方文档: https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/spring-framework-reference/web.html#spring-web
@ModelAttribute注解的两种使用方式
-
在方法上使用;
-
在方法的参数上使用。
在方法上使用
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
/**
* 返回值以myAccount为key,Account对象为值存储在模型中
*/
@ModelAttribute("myAccount")
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
/**
* 通过model.addAttribute可以添加更多的模型属性
*/
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute(accountManager.findAccount(number));
// 添加更多属性 ...
}
上面的例子中,前两个方法是通过返回值来隐式的往模型中添加属性,最后一个方法没有返回值,通过接收一个Model对象,并通过重载该对象的addAttribute方法往模型中添加任意数量的属性。
一个控制器(Controller)类中可以存在多个带有@ModelAttribute方法,当在请求控制器中的任何一个接口时,均会先执行带有@ModelAttribute注解的所有方法,当所有@ModelAttribute方法执行完成后再执行接口方法。
指定属性名称
通过@ModelAttribute("modelName")和重载Model.addAttribute(. .)方法来指定属性名称。
如果没有指定属性名称怎么办?
在这种情况下,会根据返回值类型为模型属性分配默认名称。
例:
-
返回值类型为String,默认名称为:string
-
返回值类型为List<String>,默认名称为:stringList
-
返回值类型为Map<String, String>,默认名称为:map
-
......
在方法的参数上使用
@GetMapping(path = "/test2")
@ResponseBody
public String sss(@ModelAttribute("name") String name) {
return name;
}
-
由于使用了@SessionAttributer,可能该值已经存在于模型中;
-
@ModelAttribute和接口存在于同一个控制器中,所以也可能已经存在于模型中(参见上面“在方法上使用”所述);
-
基于url变量;
-
使用默认的构造函数来实例化。