在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,下面这篇文章主要给大家介绍了关于spring mvc中@ModelAttribute注解的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。

 

前言

本文介绍在spring mvc中非常重要的注解@ModelAttribute.这个注解可以用在方法参数上,或是方法声明上。这个注解的主要作用是绑定request或是form参数到模型对象。可以使用保存在request或session中的对象来组装模型对象。注意,被@ModelAttribute注解的方法会在controller方法(@RequestMapping注解的)之前执行。因为模型对象要先于controller方法之前创建。

 

请看下面的例子

  • ModelAttributeExampleController.java 是controller类,同时包含@ModelAttribute 方法。
  • UserDetails.java是本例中的模型对象ModelAttributeExampleController.java 是controller类,同时包含@ModelAttribute 方法。
  • 最后是spring的配置文件

  

//ModelAttributeExampleController.java
package javabeat.net;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
public class ModelAttributeExampleController {
 @Autowired
 private UserDetails userDetails;
 @RequestMapping(value="/modelexample")
 public String getMethod(@ModelAttribute UserDetails userDetails){
 System.out.println("User Name : " + userDetails.getUserName());
 System.out.println("Email Id : " + userDetails.getEmailId());
 return "example";
 }
 
 //This method is invoked before the above method
 @ModelAttribute
 public UserDetails getAccount(@RequestParam String user, @RequestParam String emailId){
 System.out.println("User Value from Request Parameter : " + user);
 userDetails.setUserName(user);
 userDetails.setEmailId(emailId);
 return userDetails;
 }
}
//UserDetails.java
package javabeat.net;
 
public class UserDetails {
private String userName;
private String emailId;
public String getUserName() {
 return userName;
}
public void setUserName(String userName) {
 this.userName = userName;
}
public String getEmailId() {
 return emailId;
}
public void setEmailId(String emailId) {
 this.emailId = emailId;
}
}

  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-2.5.xsd
 http://www.springframework.org/schema/jms 
  
 http://www.springframework.org/schema/jms/spring-jms-2.5.xsd">
 <context:component-scan base-package="org.spring.examples" />
 <bean id="userDetails" class="org.spring.examples.UserDetails"/>
</beans>

- 上面的例子,getAccount方法使用@ModelAttribute注解。这意味着方法会在controller的方法之前执行。这个方法会使用request的参数设置模型对象。这是一种在方法中设置值的途径。

- 另一种@ModelAttribute注解的使用方法,是用在方法的参数上。在调用方法的时候,模型的值会被注入。这在实际使用时非常简单。将表单属性映射到模型对象时,这个注解非常有用。

 

一、@ModelAttribute注释方法 

例子(1),(2),(3)类似,被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。    

(1)@ModelAttribute注释void返回值的方法

@Controller
public class HelloWorldController {
  @ModelAttribute
  public void populateModel(@RequestParam String abc, Model model) { 
   model.addAttribute("attributeName", abc);
  }
  @RequestMapping(value = "/helloWorld")
  public String helloWorld() {
   return "helloWorld";
  }
}

 

这个例子,在获得请求/helloWorld 后,populateModel方法在helloWorld方法之前先被调用,它把请求参数(/helloWorld?abc=text)加入到一个名为attributeName的model属性中,在它执行后helloWorld被调用,返回视图名helloWorld和model已由@ModelAttribute方法生产好了。

这个例子中model属性名称和model属性对象有model.addAttribute()实现,不过前提是要在方法中加入一个Model类型的参数。

当URL或者post中不包含次参数时,会报错,其实不需要这个方法,完全可以把请求的方法写成,这样缺少此参数也不会出错

@RequestMapping(value = "/helloWorld") 
public String helloWorld(String abc) { 
   return "helloWorld";
}

 

(2)@ModelAttribute注释返回具体类的方法

@ModelAttribute
public Account addAccount(@RequestParam String number) { 
  return accountManager.findAccount(number);
}

 

 这种情况,model属性的名称没有指定,它由返回类型隐含表示,如这个方法返回Account类型,那么这个model属性的名称是account。

这个例子中model属性名称有返回对象类型隐含表示,model属性对象就是方法的返回值。它无须要特定的参数。

(3)@ModelAttribute(value="")注释返回具体类的方法

@Controller
public class HelloWorldController {
  @ModelAttribute("attributeName")
  public String addAccount(@RequestParam String abc) { 
   return abc;
  }
  @RequestMapping(value = "/helloWorld")
  public String helloWorld() {
   return "helloWorld";
  }
}

 

这个例子中使用@ModelAttribute注释的value属性,来指定model属性的名称。model属性对象就是方法的返回值。它无须要特定的参数。

(4)@ModelAttribute和@RequestMapping同时注释一个方法

@Controller
public class HelloWorldController {
  @RequestMapping(value = "/helloWorld.do") 
  @ModelAttribute("attributeName")
  public String helloWorld() {
   return "hi";
  }
}

 

这时这个方法的返回值并不是表示一个视图名称,而是model属性的值,视图名称由RequestToViewNameTranslator根据请求"/helloWorld.do"转换为逻辑视图helloWorld。

Model属性名称有@ModelAttribute(value=””)指定,相当于在request中封装了key=attributeName,value=hi。

二、@ModelAttribute注释一个方法的参数

(1)从model中获取    

@Controller
public class HelloWorldController {
  @ModelAttribute("user")
  public User addAccount() {
   return new User("jz","123");
  }
  @RequestMapping(value = "/helloWorld")
  public String helloWorld(@ModelAttribute("user") User user) { 
   user.setUserName("jizhou");
   return "helloWorld";
  }
}

 

在这个例子里, @ModelAttribute("user") User user注释方法参数,参数user的值来源于addAccount()方法中的model属性。

此时如果方法体没有标注@SessionAttributes("user") ,那么scope为request,如果标注了,那么scope为session

(2)从Form表单或URL参数中获取(实际上,不做此注释也能拿到user对象) 

@Controller
public class HelloWorldController {
  @RequestMapping(value = "/helloWorld")
  public String helloWorld(@ModelAttribute User user) { 
   return "helloWorld";
  }
}

 

注意这时候这个User类一定要有没有参数的构造函数。