Spring boot @ModelAttribute标注的实现

网友投稿 441 2023-07-01

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();

@ModelAttribhttp://ute

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 = (http://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;

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring @Valid @Validated实现验证
下一篇:Spring基于xml文件配置Bean过程详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~