Spring boot @ModelAttribute标注的实现
作者:麦穗儿
这篇文章主要介绍了Spring boot @ModelAttribute标注的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
@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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。