适用范围
- 方法
- 参数
标注在方法上
@ModelAttribute标注在方法上时表明这个方法是用于给Model模型添加一个或多个属性。
标注了@ModelAttribute的方法会在访问@RequestMapping方法前先执行(同一个类中),这个方法通常用于参加通用的属性。
一个类中可以有任意个@ModelAttribute标注的方法,它们都会在这个类的@RequestMapping方法前执行
例子:
//某个Controller中的方法
@ModelAttribute
public Version getVersion(){
return new Version();
}
@RequestMapping("/one")
public String show(){
return "testmodelattr";
}
testmodelattr.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p> ${version } </p>
</body>
</html>
这样,当我们访问/one时,标注了@ModelAttribute的getVersion方法会被执行,上面这种写法会以(“返回类型(首字母小写)”,“返回值”)的形式添加一个属性在Model中,效果等同于在@RequestMapping为Model装配了一个属性,在这里向Model中添加了(“version”, new Version()).于是我们在testmodelattr.jsp可以得到version属性的值。
我们也可以显示的设定属性的名称,在@ModelAttribute添加value属性:@ModelAttribute(“myversion”).这样,在jsp中就可以通过$(myversion)访问。
也可以直接在标注了@ModelAttribute的方法上添加一个Model参数,直接为这个参数添加属性和值。也可以达到同样的效果,并且可以配置多个属性。
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute(accountManager.findAccount(number));//没有指定名称默认为类型名,首字母小写
model.addAttribute("modelname", value);
// add more ...
}
标注了@ModelAttribute的方法同时也可以标注@RequestMapping方法,只此时方法的返回值将不是解析成视图,而是Model的属性值。视图名将会通过RequestToViewNameTranslator解析。
标注在方法参数上
待续