Spring ModelAttribute注解

Spring ModelAttribute注解


Spring ModelAttribute注解,主要有三个作用:
1. 注解在参数上。
绑定请求参数到命令对象,并把命令对象添加到Model,用于视图页面展示。
@RequestMapping("/save")  
public String save(@ModelAttribute(“bwf”) Company bwf) {  
    service.save(bwf);  
    return "result";  
}  
它的作用是将该绑定对象以“bwf”为key,添加Model对象中,供视图页面展示使用。页面中可以使用${bwf.name}来获取绑定对象的属性。
2. 注解在普通方法上(非RequestMapping注解的方法)。
@ModelAttribute("bwf")  
public User addCompany(Company bwf) {  
    return new Company("1","博为峰");  
}  
假设此方法是写在某个Controller内,那么执行该Controller内带有@RequestMapping注解的方法之前,都会先执行此addCompany方法,并且在model对象中将添加bwf对象。
3. 注解在@RequestMapping 方法返回值上。
绑定该方法的返回值到Model对象,用于视图页面展示时使用。@ModelAttribute 注解的返回值会覆盖@RequestMapping 注解方法中的同名命令对象