类似于 JSP-Servlet 中的 req.setAttribute 、 req.getSession().setAttribute ...
--> 最后在 JSP 用 EL 表达式取得这些数据对象,
STEP-1 传递模型数据的三种方式
package spittr.web; import static org.springframework.web.bind.annotation.RequestMethod.GET; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import spittr.Spittle; import spittr.data.SpittleRepository; @Controller public class SpittleController { private SpittleRepository spittleRepository; @Autowired public SpittleController(SpittleRepository spittleRepository) { this.spittleRepository = spittleRepository; } @RequestMapping(value="/spittles", method=GET) public List<Spittle> spittles() { return spittleRepository.findSpittles(Long.MAX_VALUE, 20); } // 采用用无 String 的方式传递模型数据到视图 // --> 属性名推断为 spittleList // --> 视图名称推断为 spittles --> 去掉了 / // public String spittles(Model model) { // model.addAttribute(spittleRepository.findSpittles(Long.MAX_VALUE, 20)); // return "spittles"; // } 这是等价方法-1:半自定义 --> 自定义视图名 // public String spittles(Model model) { // model.addAttribute("myList", spittleRepository.findSpittles(Long.MAX_VALUE, 20)); // return "spittles"; // } 这是等价方法-2:高度自定义。 --> 自定义视图名以及属性名 }
STEP-2 在 JSP 页面中获取数据
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="s" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <html> <head> <title>Spitter</title> <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />" > </head> <body> <div class="spittleForm"> <h1>Spit it out...</h1> <form method="POST" name="spittleForm"> <input type="hidden" name="latitude"> <input type="hidden" name="longitude"> <textarea name="message" cols="80" rows="5"></textarea><br/> <input type="submit" value="Add" /> </form> </div> <div class="listTitle"> <h1>Recent Spittles</h1> <ul class="spittleList"> <c:forEach items="${spittleList}" var="spittle" > <li id="spittle_<c:out value="spittle.id"/>"> <div class="spittleMessage"><c:out value="${spittle.message}" /></div> <div> <span class="spittleTime"><c:out value="${spittle.time}" /></span> <span class="spittleLocation">(<c:out value="${spittle.latitude}" />, <c:out value="${spittle.longitude}" />)</span> </div> </li> </c:forEach> </ul> <%-- <c:if test="${fn:length(spittleList) gt 20}"> <hr /> <s:url value="/spittles?count=${nextCount}" var="more_url" /> <a href="${more_url}">Show more</a> </c:if> --%> </div> </body> </html>