@ModelAttribute可以注释方法和参数
@ModelAttribute注释方法该方法会在controller的所有方法之前被执行。通过Model将value设定到相应的key中。
(1)注释返回值为void的方法,通过传入Model添加属性值
@RestController @RequestMapping("/usrcontroller") public class UserController { UserService us = new UserService(); @ModelAttribute public void findUserById(@RequestParam Long uid, Model model) { model.addAttribute("user", us.getUser(uid)); } @GetMapping(path="/getuser") @ResponseBody public String getUser(Model model) { User u = (User)(model.getAttribute("user")); System.out.println(u.name); return u.name; } }
(2)注释返回值为具体类型的。通过添加属性(属性名为返回值的头字母小写,例如返回值为Group,属性为group)将返回值添加
实际结果类似与model.addAttribute("returnvaluename", var);
@RestController @RequestMapping("/groupcontroller") public class GroupController { @ModelAttribute public Group getGroupId(@RequestParam Long gid) { Group g = new Group(); g.groupName = "group_"+gid; g.groupId = gid; return g; //same as Model.addAttribute("group", g) } @GetMapping(path="/getgroup") @ResponseBody public String getGroup(Model model) { Group g = (Group)model.getAttribute("group"); String gStr = "group(id:" + g.groupId + "," + g.groupName + ")"; System.out.println(gStr); return gStr; } }
(3)指定属性的名称
//类似于Model.addAttribute("defaultuser", User) @ModelAttribute("defaultuser") public User createDefaultUser() { return new User("defaultUsr","SH", 22, true); } @GetMapping(path="/checkdefaultuser") @ResponseBody public String checkDefaultUser(@ModelAttribute("defaultuser") User dfUsr) { String dfUsrStr = "Default user("+dfUsr.name + "," + dfUsr.address + "," + dfUsr.age + "," + dfUsr.isMan + ")"; System.out.println(dfUsrStr); return dfUsrStr; }
@ModelAttribute("defaultuser") public User createDefaultUser() { return new User("defaultUsr","SH", 22, true); } @GetMapping(path="/checkdefaultuser") @ResponseBody public String checkDefaultUser(@ModelAttribute("defaultuser") User dfUsr) { String dfUsrStr = "Default user("+dfUsr.name + "," + dfUsr.address + "," + dfUsr.age + "," + dfUsr.isMan + ")"; System.out.println(dfUsrStr); return dfUsrStr; }