欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring boot @ModelAttribute标注的实现

程序员文章站 2023-11-13 16:01:28
@modelattribute可以注释方法和参数 @modelattribute注释方法 @modelattribute注释方法该方法会在controller的所有方法之前被执...

@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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。