spring 3 MVC 笔记 4

@ModelAttribute 的使用

手册上的解释:

@ModelAttribute has two usage scenarios in controllers. When you place it on a method parameter, @ModelAttribute maps a model attribute to the specific, annotated method parameter (see the processSubmit() method below). This is how the controller gets a reference to the object holding the data entered in the form.

You can also use @ModelAttribute at the method level to provide reference data for the model (see the populatePetTypes() method in the following example). For this usage the method signature can contain the same types as documented previously for the @RequestMappingannotation.

Note

@ModelAttribute annotated methods are executed before the chosen @RequestMapping annotated handler method. They effectively pre-populate the implicit model with specific attributes, often loaded from a database. Such an attribute can then already be accessed through @ModelAttribute annotated handler method parameters in the chosen handler method, potentially with binding and validation applied to it.

@ModelAttribute有两种用法

1. 方法级

2.方法参数级

package home.dong.springmvc;

import home.dong.springmvc.beans.User;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @ModelAttribute 注释有方法级和参数级
 * 
 * 方法级时
 * @ModelAttribute(value="xxxxx") 相当于 reqeust.setAttribute("xxxxx", object);
 * @ModelAttribute的 value 相当于 request attribute 的键值。 有此注解的方法返回值即是request attribute 的值。
 * 
 * 
 * 参数级
 * 用于接受页面参数传递并转换成java bean.同时放入reqeust中传递。
 * @author tiger
 * 
 */
@Controller
@RequestMapping("/modelAttr")
public class ModelAtrrTest {

	/**
	 * 在调用请求(request mapping)之前会先调用此方法
	 * 
	 * @return
	 */
	@ModelAttribute(value = "userList")
	public List<User> loadUsers() {
		List<User> list = new ArrayList<User>();
		for (int i = 0; i < 5; i++) {
			User u = new User();
			u.setUserName("User_Name_" + i);
			u.setAge(20 + i);
			u.setEmail("User_Name_" + i + "@home.com");
			list.add(u);

		}
		return list;
	}

	/**
	 * 在调用请求(request mapping)之前会先调用次方法
	 * 
	 * @return
	 */
	@ModelAttribute("currencies")
	public List<String> getAllCurrencies() {
		// Prepare data
		List<String> currencies = new ArrayList<String>();
		currencies.add("Dollar");
		currencies.add("Yen");
		currencies.add("Pound");
		currencies.add("Euro");
		currencies.add("Dinar");

		return currencies;
	}

	/**
	 * 此路径的请求会先调用上面两个有@ModelAttribute注解的方法。
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String viewAllUsers() {
		return "users";
	}

	/**
	 * 此路径的请求会先调用上面两个有@ModelAttribute注解的方法。 如果方法添加了Model类型的参数,则此参数中已经含有了键值为@ModelAttribute的value的对象的引用。 也就是说
	 * 下面 model.containsAttribute("currencies"); 和 model.containsAttribute("userList"); 将会是 True
	 * 
	 * @return
	 */
	@RequestMapping(value = "/edit/{userName}", method = RequestMethod.GET)
	public String eidtUser(@PathVariable String userName, Model model) {

		System.out.println(model.containsAttribute("currencies"));
		System.out.println(model.containsAttribute("userList"));

		User u = new User();
		u.setUserName(userName);
		u.setAge(20);
		u.setEmail("User_Name@home.com");
		model.addAttribute("user", u);
		return "editUser";
	}

	
	
	/**
	 * 将页面接收到的user属性值转换成User对象,并以"auser"为key添加到ModelAttribute中,相当于reqeust.setAttribute("auser",user);
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value="save/{userName}",method=RequestMethod.POST)
	public String saveUser(@ModelAttribute("auser") User user) {
		System.out.println(user.getAge()+"===========");
		System.out.println(user.getEmail()+"===========");
		return "users";
	}
}
 

users.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<c:if test="${auser!=null}">
${auser.age}
</c:if>
	<h3>User List Page</h3>
	
<table>  
    <tr>  
        <td width="150">user name</td>  
        <td width="150">age</td>  
        <td width="100">email</td>  
        <td></td>
    </tr>  
    <c:forEach items="${userList}" var="u">  
        <tr>  
            <td><c:out value="${u.userName}" /></td>  
            <td><c:out value="${u.age}" /></td>  
            <td><c:out value="${u.email}" />
            <a href="<c:url value="/modelAttr/edit/${u.userName}" />">edit</a>
            </td>  
        </tr>  
    </c:forEach>  
</table>
</body>
</html>

editUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>Edit User</h3>
	<form:form modelAttribute="user" action="/Lesson1_SpringMVC/modelAttr/save/${user.userName}" method="POST">
	 
	 User name:<form:input path="userName"/><br />
	 age:<form:input path="age"/><br />
	 email: <form:input path="email"/><br />
	 <input type="submit" value="submit">
	 </form:form>
</body>
</html>


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值