SpringMVC案例五:@ModelAttribute

控制器中:

@Autowired
private DeptService deptService;

@ModelAttribute("deptList")
public List<Dept> getAllDept(){
	return this.deptService.getAll();
}

@RequestMapping("testModelAttribute")
public String testModelAttribute() {		
	return "test";
}

jsp页面:

<select>
	<c:forEach items="${deptList }" var="dept">
		<option value="${ dept.deptno }">${ dept.dname }option>
	c:forEach>
select>

说明:

@ModelAttribute
1)在方法定义中使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了 @ModelAttribute 的方法,并将这些方法的返回值添加到模型中
2)在多个处理器方法中都需要相同数据的时候使用,好处:代码重用
3)在处理器方法的形参前加入@ModelAttribute注解,会在Model对象中添加该属性,便于响应结果页面得到该属性值
4)一般用在简单数据类型上(pojo会自动添加到Model对象中,也可以用于修改pojo在model中的属性名)

@RequestMapping("testModelAttribute")
public String testModelAttribute(@ModelAttribute("d") Dept dept,@ModelAttribute("age") Integer age) {		
	return "test";
}

你可能感兴趣的:(其他框架,SpringMVC从入门到精通)