(八)SpringMVC @ModelAttribute注解
(八)SpringMVC @ModelAttribute注解
1 、@ModelAttribute作用
@ModelAttribute注解的作用,将请求参数绑定到Model对象。被@ModelAttribute注释的方法会在Controller每个方法执行前被执行(如果在一个Controller映射到多个URL时,要谨慎使用)。
2 、@ModelAttribute使用位置
在SpringMVC的Controller中使用@ModelAttribute
时,其位置包括下面三种:
- 应用在方法上
- 应用在方法的参数上
- 应用在方法上,并且方法同时使用@RequestMapping
2.1、应用在方法上
2.1.1 用在无返回值的方法
1)编写ModelAttributeController
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @ModelAttribute注解的使用 */ @Controller public class ModelAttributeController { //没有返回值的情况 @ModelAttribute public void myModel(@RequestParam(required = false) String name, Model model) { model.addAttribute("name", name); } @RequestMapping(value = "/model") public String model() { return "success"; } }
在model方法之前会执行myModel方法。因此在myModel方法中,请求传递的name参数存入Model对象,该参数值也会随着model方法带到JSP页面中。
2.1.2 用在带返回值的方法
1)ModelController类
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @ModelAttribute注解的使用 * 一点教程网 - www.yiidian.com */ @Controller public class ModelAttributeController { /** * 带返回值的情况 * @param name */ @ModelAttribute("name") public String myModel(@RequestParam(required = false) String name) { return name; } @RequestMapping(value = "/model") public String model() { return "success"; } }
带有返回值的情况,其实就是自动把方法返回值存入Model对象,@ModelAttribute 的value属性就是 Model的 key。相当于
model.addAttribute("name",name);
2.2、应用在方法的参数上
@ModelAttribute("name") public String myModel(@RequestParam(required = false) String name) { return name; } //应用在方法的参数行 @RequestMapping(value = "/model") public String model(@ModelAttribute("name") String name) { System.out.println("name="+name); return "success"; }
@ModelAttribute注解应用在方法的参数上,其实就是从Model对象中取出对应的属性值。
2.3、方法上 + @RequestMapping
//@ModelAttribute,@RequestMapping同时放在方法上 @RequestMapping(value = "/model") @ModelAttribute("name") public String model(@RequestParam(required = false) String name) { return name; }
@ModelAttribute和@RequestMapping同时应用在方法上的时候,有两层意义:
- 方法的返回值会存入Model对象中,key就是ModelAttribute的value属性值
- 方法的返回值不再是方法的访问路径,访问路径会变为@RequestMapping的value值,例如:@RequestMapping(value = "/model") 跳转的页面是model.jsp页面。
总之,@ModelAttribute
注解的使用的方法有很多种,非常灵活,我们可以根据业务需求选择使用。