Implementation of spring boot @ modelattribute annotation
@Modelattribute can annotate methods and parameters
@Modelattribute annotation method
@Modelattribute annotates the method, which will be executed before all the methods of the controller. Set the value to the corresponding key through the model.
(1) Comment on the method whose return value is void, and add the attribute value by passing in the 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) Annotation returns a value of a specific type. Add an attribute (the attribute name is lowercase, for example, the return value is group, and the attribute is group) to add the return value. The actual result is similar to 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) Specifies the name of the property
//类似于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; }
@Parameters of the modeattribute annotation method
@modelattribute("defaultuser") public User createDefaultUser() { return new User("defaultUsr"," + dfUsr.isMan + ")"; System.out.println(dfUsrStr); return dfUsrStr; }
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.