Implementation of spring boot @ modelattribute annotation

Time:2020-10-15

@Modelattribute can annotate methods and parameters

@Modelattribute annotation method

@Modelattribute annotates a method that is executed before all methods of the controller. Set the value to the corresponding key through the model.

(1) Comment the method that returns the value of void, and adds the property 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) The return value of the annotation is of a specific type. Add the return value by adding an attribute (the property name is the lowercase letter of the return value, for example, the return value is group, and the property is group)
The actual results are similar to those of 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

//Similar to 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","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;
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.