1. 程式人生 > >Spring MVC 之傳遞模型數據到視圖中

Spring MVC 之傳遞模型數據到視圖中

sage size efi ram fix post head bmi 傳遞

類似於 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>

Spring MVC 之傳遞模型數據到視圖中