@ModelAttribute可以注释方法和参数
@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; }
@ModeAttribute注释方法的参数
@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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。