可参考
被@ModelAttribute注释的方法会在此Handler每个方法执行前被执行
@ModelAttribute修饰void返回值的方法
<a href="springmvc/testModelAttributeVoid?username='Bruce'">testModelAttributeVoid</a>
@ModelAttribute
public void modelAttributeVoid(
@RequestParam(value="username") String username
,Model model){
model.addAttribute("username", username);//model中数据会被被放到request域中
}
@RequestMapping("/testModelAttributeVoid")
public String testModelAttributeVoid(){
return MODELATTRIBUTE;
}
username:${requestScope.username}
@ModelAttribute修饰返回Object的方法
<a href="springmvc/testModelAttributeObject">testModelAttributeObject</a>
@ModelAttribute(value="myEmp")//指定model key
public Emp modelAttributeObject(){
Emp emp = new Emp(1,"George","boy");
return emp;
/*在@ModelAttribute没有指明key的情况下,return一个对象
* 那么model==该对象,且model的key==类首字母小写
* 如"emp"*/
}
@RequestMapping("/testModelAttributeObject")
public String testModelAttributeObject(){
return MODELATTRIBUTE;
}
<%-- emp:${requestScope.emp} --%>
emp:${requestScope.myEmp}
@ModelAttribute 对象合并
<a href="springmvc/testModelAttributeCombine">testModelAttributeCombine</a>
@ModelAttribute(value="myEmp2")//指定model key
public Emp modelAttributeCombine(){
Emp emp = new Emp(1,"George","boy");
return emp;
}
@RequestMapping("/testModelAttributeCombine")
public String testModelAttributeCombine(
@ModelAttribute(value="myEmp2") Emp emp){
emp.setName("Murphy");
return MODELATTRIBUTE;
/* 在目标方法中获取的emp是被
* @ModelAttribute修改且key为myEmp2的model数据*/
}
emp2:${requestScope.myEmp2}
//emp2:Emp(id=1, name=Murphy, sex=boy)
网友评论