@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; } } @H_403_11@(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; } } @H_403_11@//类似于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; } @H_403_11@@ModeAttribute注释方法的参数
@modelattribute("defaultuser") public User createDefaultUser() { return new User("defaultUsr"," + dfUsr.isMan + ")"; System.out.println(dfUsrStr); return dfUsrStr; } @H_403_11@ 原文链接:/java/534914.html