spring mvc:@ModelAttribute的作用

@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时:  通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

A) @SessionAttributes 启用的attribute 对象上;

B) @ModelAttribute 用于方法上时指定的model对象;

C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。


用到方法上@ModelAttribute的示例代码:

[java]  view plain copy
  1. // Add one attribute  
  2. // The return value of the method is added to the model under the name "account"  
  3. // You can customize the name via @ModelAttribute("myAccount")  
  4.   
  5. @ModelAttribute  
  6. public Account addAccount(@RequestParam String number) {  
  7.     return accountManager.findAccount(number);  
  8. }  

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);


用在参数上的@ModelAttribute示例代码:

[java]  view plain copy
  1. @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
  2. public String processSubmit(@ModelAttribute Pet pet) {  
  3.      
  4. }  
首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

猜你喜欢

转载自blog.csdn.net/happydecai/article/details/80406890
今日推荐