本篇文章給大家分享的是有關(guān)Springboot中怎么實(shí)現(xiàn)@ModelAttribute標(biāo)注,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站建設(shè)、成都做網(wǎng)站與策劃設(shè)計(jì),阿拉善盟網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)十多年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:阿拉善盟等地區(qū)。阿拉善盟做網(wǎng)站價(jià)格咨詢:18980820575
@ModelAttribute可以注釋方法和參數(shù)
@ModelAttribute注釋方法
@ModelAttribute注釋方法該方法會在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")@ResponseBodypublic 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")@ResponseBodypublic String checkDefaultUser(@ModelAttribute("defaultuser") User dfUsr) { String dfUsrStr = "Default user("+dfUsr.name + "," + dfUsr.address + "," + dfUsr.age + "," + dfUsr.isMan + ")"; System.out.println(dfUsrStr); return dfUsrStr;}
以上就是Springboot中怎么實(shí)現(xiàn)@ModelAttribute標(biāo)注,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。