@ModelAttribute也可以做为Model输出到View时使用,比如:
测试例子
package com.my.controller; import java.util.ArrayList;
import java.util.List; 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.RequestMethod; import com.my.controller.bean.Account; @Controller
@RequestMapping(value="attr")
public class TestModelAttributeController { private static List<Account> accounts = new ArrayList<Account>();
{
accounts.add(new Account());
accounts.add(new Account()); Account ac1 = accounts.get(0);
Account ac2 = accounts.get(1); ac1.setUserName("Robin");
ac1.setPassword("123123"); ac2.setUserName("Lucy");
ac2.setPassword("123456");
} @RequestMapping(method=RequestMethod.GET)
public String index() {
System.out.println("index");
return "TestModelAttribute/index";
} @ModelAttribute("accounts")
public List<Account> getAccounts() {
System.out.println("getAccounts");
return accounts;
} }
<%@ 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://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/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>TestModelAttribute</title>
</head>
<body>
<c:forEach items="${accounts}" var="item">
<c:out value="${item.userName}"></c:out><br/>
</c:forEach>
</body>
</html>
页面将输出:
在Console中输出为:
这里可以看到,运行的先后次序为:先调用getAccounts(),再调用index()。