您好,登錄后才能下訂單哦!
@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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。