@ModelAttribute用法详解

@ModelAttribute

  • 该Controller类所有方法执行前,先调用此@ModelAttribute方法,可用于注解和方法参数中。
  • @ModelAttribute注解用于将请求参数绑定到Model对象

使用方式一:注解void返回值的方法

  • 此方法在@RequestMapping注解的方法之前执行,通过方法model.addAttribute(key,value)绑定数据,通过login方法的model.containsAttribute(“username”)测试userModel方法是否起作用,因为@ModelAttribute注释的方法在请求方法之前起作用。
@Controller
@RequestMapping(value="/")
public class TestModelAttributeController {
	
	@RequestMapping(value="/result")
	public String login(Model model) {
		//如果测试成功,控制台输出true
		System.out.println(model.containsAttribute("username"));
	    System.out.println(model.containsAttribute("pwd"));
		return "result"; 
	}
	@ModelAttribute
	public void user(
			@RequestParam("username") String username,
			@RequestParam("pwd") String pwd,Model model) {
		 model.addAttribute("username", username);
		 model.addAttribute("pwd", pwd);
	}
}

使用方法二:@ModelAttribute(“xxx”)注释返回具体类的方法

  • @ModelAttribute的value值“xxx”作为model的attributeName,userModel方法返回值作为attribute属性的值
@Controller
@RequestMapping(value="/")
public class TestModelAttributeController{
	
	@RequestMapping(value="result")
	public String login(Model model) {
		model.containsAttribute("username");
		return "result";
	}
    /*
    * 返回的是username的值
    *相当于model.addAttribute("username", username);
    */
	@ModelAttribute(value="username")
	public String userModel(@RequestParam("username") String username) {
		return username;
	}
}

使用方式三:@ModelAttribute注释返回具体类的方法

@ModelAttribute
public User userModel(@RequestParam("username") String username,@RequestParam("pwd") String pwd){
    User  user = new User(username,pwd);
    return user;
}
public String login(Model model){
    System.out.println(model.containsAttribute("username"));
    System.out.println(model.containsAttribute("pwd"));

    return modelAttribute/result";
}

使用方式四:@ModelAttribute(“xxx”)和@RequestMapping("/yyy’)同时注释的有返回值的方法

  • @ModelAttribute(“xxx”)的属性值作为model的attributeName,login方法返回值作为attributeName的属性值;
  • RequestMapping("/yyy")作为请求路径,也同时作为视图名,即跳转页面的名称
@Controller
@RequestMapping(value="/")
public class TestModelAttributeController{
	
	@ModelAttribute("username")
	@RequestMapping(value="/result")
	public String login(@RequestParam("username") String username,Model model) {
		
		System.out.println(model.containsAttribute("username"));
		return username;	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41357573/article/details/84339866
今日推荐