@ModelAttribute

本文介绍了Spring MVC中@ModelAttribute注解的两种使用方式:在方法上使用和在方法参数上使用。在方法上使用时,返回值会被添加到模型中;在参数上使用时,可以从模型、session、URL变量或默认构造函数获取值。多个@ModelAttribute方法会在调用具体接口前执行,用于预填充模型数据。
摘要由CSDN通过智能技术生成
                                                                 能否请你动动手指,留下你的一键三连。
 
官方文档: https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/spring-framework-reference/web.html#spring-web
 

@ModelAttribute注解的两种使用方式
  1. 在方法上使用;
  2. 在方法的参数上使用。
 
在方法上使用
 
@ModelAttribute
public Account addAccount(@RequestParam String number) {
     return accountManager.findAccount(number);
}

/**
* 返回值以myAccount为key,Account对象为值存储在模型中
*/
@ModelAttribute("myAccount")
public Account addAccount(@RequestParam String number) {
     return accountManager.findAccount(number);
}

/**
* 通过model.addAttribute可以添加更多的模型属性
*/
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
    model.addAttribute(accountManager.findAccount(number));
    // 添加更多属性 ...
}

 

    上面的例子中,前两个方法是通过返回值来隐式的往模型中添加属性,最后一个方法没有返回值,通过接收一个Model对象,并通过重载该对象的addAttribute方法往模型中添加任意数量的属性。
 
    一个控制器(Controller)类中可以存在多个带有@ModelAttribute方法,当在请求控制器中的任何一个接口时,均会先执行带有@ModelAttribute注解的所有方法,当所有@ModelAttribute方法执行完成后再执行接口方法。
 
指定属性名称
    通过@ModelAttribute("modelName")和重载Model.addAttribute(. .)方法来指定属性名称。
 
如果没有指定属性名称怎么办?
    在这种情况下,会根据返回值类型为模型属性分配默认名称。
    例:
  1.  返回值类型为String,默认名称为:string
  2. 返回值类型为List<String>,默认名称为:stringList
  3. 返回值类型为Map<String, String>,默认名称为:map
  4.  ......
 
在方法的参数上使用
    
@GetMapping(path = "/test2")
@ResponseBody
public String sss(@ModelAttribute("name") String name) {
    return name;
}

 

从上面的示例代码来看,参数name的值可能从以下几个地方来:
  1. 由于使用了@SessionAttributer,可能该值已经存在于模型中;
  2. @ModelAttribute和接口存在于同一个控制器中,所以也可能已经存在于模型中(参见上面“在方法上使用”所述);
  3. 基于url变量;
  4. 使用默认的构造函数来实例化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值