1. 程式人生 > 程式設計 >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"," + dfUsr.isMan + ")";
  System.out.println(dfUsrStr);
  return dfUsrStr;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。