1 注释方法
被@ModelAttribute
注释的方法会在此controller
每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。
1.1 注释void返回值的方法

在获得请求
/helloWorld
后,populateModel
在helloWorld
之前被调用,它把请求参数/helloWorld?abc=text
加入到一个名为
attributeName
的model属性中,在它执行后helloWorld
被调用,返回视图名helloWorld
和model已由@ModelAttribute
方法生产好了
这个例子中model属性名称和model属性对象由model.addAttribute()
实现
不过前提是要在方法中加入一个Model类型的参数
,当URL或者post中不包含此参数时,会报错


其实不需要这个方法,完全可以把请求的方法写成,这样缺少此参数也不会出错

1.2 注释返回具体类的方法
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
model属性的名称没有指定,它由返回类型隐含表示,model属性对象就是方法的返回值
如这个方法返回Account类型,那么这个model属性的名称是account
1.3 注释返回具体类的方法

@ModelAttribute
注释的value属性,指定model属性的名称model属性对象就是方法的返回值,无须要特定的参数
1.4 和@RequestMapping同时注释一个方法

该方法的返回值并非表示一个视图名称,而是model属性的值,视图名称由
RequestToViewNameTranslator
根据请求"/helloWorld.do"
转换为逻辑视图helloWorld
Model属性名称由@ModelAttribute(value=””)
指定,相当于在request中封装了key=attributeName,value=hi
2 注释一个方法的参数
2.1 从model中获取

@ModelAttribute("user") User user
注释方法参数,参数user的值来源于addAccount()方法中的model属性
此时如果方法体没有标注@SessionAttributes("user")
,那么scope
为request
,如果标注了,那么scope
为session
2.2 从Form表单或URL参数中获取(实际上,不做此注释也能拿到user对象)

注意这时候这个User类一定要有没有参数的构造函数
网友评论