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("[email protected]");
		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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章