@ModelAttribute可以注釋方法和參數(shù)
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對(duì)這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊、網(wǎng)頁空間、營銷軟件、網(wǎng)站建設(shè)、老河口網(wǎng)站維護(hù)、網(wǎng)站推廣。
@ModelAttribute注釋方法
@ModelAttribute注釋方法該方法會(huì)在controller的所有方法之前被執(zhí)行。通過Model將value設(shè)定到相應(yīng)的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)將返回值添加
實(shí)際結(jié)果類似與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注釋方法的參數(shù)
@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; }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。