Spring Boo 2.0 教程 | @ModelAttribute 注解

欢迎关注微信公众号: 小哈学Java
文章首发于个人网站: https://www.exception.site/springboot/spring-boot-model-attribute

Spring Boot 2.0 中的注解 @ModelAttribute 有什么作用呢?

通常情况下,我们会将 @ModelAttribute 注解放置在 Controller 中的某个方法上,那么,如果您在请求这个 Controller 中定义的 URI 时,会首先调用这个被注解的方法,并将该方法的结果作为 Model 的属性,然后才会调用对应 URI 的处理方法。

一、@ModelAttribute 使用场景

我们通常会通过 @ModelAttribute 来向某个 Controller 中需要的公共模型 Model 中添加数据。如下面的示例代码所示。

二、示例代码

@ModelAttribute
public void findUserById(@PathVariable("userId") Long userId, Model model) {
    model.addAttribute("user", userService.findUserById(userId));
}

@GetMapping("/user/{userId}")
public String findUser(Model model) {
    System.out.println(model.containsAttribute("user"));
    return "success !";
}

当我们请求接口 /user/1 时,会先调用 findUserById 方法,方法内,通过 userId 查询到对应的 User 对象放置到 Model 模型中。

需要注意,如果您仅仅只是添加一个对象到 Model 模型中,上面的代码还可以再精炼一点:

@ModelAttribute
public User findUserById(@PathVariable("userId") Long userId) {
    return userService.findUserById(userId);
}

通过上述的代码,返回的 User 对象会被自动添加到 Model 模型中,就相当于您手动调用了 model.addAttribute(user) 方法。

欢迎关注公众号: 小哈学Java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值