栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@ModelAttribute的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@ModelAttribute的使用

目录

1.注释返回值为void的方法

2.注释返回值为具体对象的方法

3.对象合并


写在前面,我使用的是springboot2.6.7来进行测试。

1.注释返回值为void的方法
@Controller
public class HelloController {

    @ModelAttribute
    public void addMessage(String message, Model model){
        model.addAttribute("message",message);
    }

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

当执行http://localhost:8080/hello?message=xxx的时候,先执行addMessage方法获取message参数的值放在model中,在视图中可以获取。

 

 

2.注释返回值为具体对象的方法
    @ModelAttribute(value = "myUser")
    public User addUser() {
        User user = new User();
        user.setName("小王");
        user.setSex("男");
        user.setAge(12);
        return user;
    }

    @GetMapping("/hello2")
    public String hello() {
        return "hello" ;
    }

在执行/hello2之前会先调用addUser方法,会隐式的执行model.addAttribute("myUser",user);

 这里我们在注解的后面指定了valu的值为myUser,因此这里model中的attributeName就为myUser,如果我们不指定Value的值,那么默认就是返回类型的类名的小写,这里如果我们不写那么就是这样的model.addAttribute("user",user);

 页面如下

 

执行方法

 

3.对象合并

比如我们在修改某条记录的时候,我们仅仅是修改了某一个字段的值,其他的字段值不变。这里我们模拟一下。

    
    @ModelAttribute(value = "myUser")
    public User getUser() {
        User user = new User();
        user.setName("小王");
        user.setSex("男");
        user.setAge(12);
        return user;
    }

    
    @GetMapping("/hello3")
    public String hello(@ModelAttribute(value = "myUser") User user) {
        user.setAge(32);
        return "hello" ;
    }

访问方法看结果

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914663.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号