簡體   English   中英

如何在 JSTL 中遍歷 object 列表

[英]How to loop over a list of object in JSTL

在此處輸入圖像描述我有以下列表,該列表來自 class 通過 toString 方法。 我將 modelAndView object 中的列表傳遞給 jsp 頁面。 現在我想遍歷列表並在 jsp 頁面中創建一個表。 請指導。

 List<LocationStats> allStates = [LocationStats{state='Fujian', country='Afghanistan', latestTotalCases=51526}, LocationStats{state='Guangdong', country='Albania', latestTotalCases=59438}] ;

////////////////////// LocationStats.JAVA ////////////////// /////////////////

public class LocationStats {
    
    private String state;
    private String country;
    private int latestTotalCases;
    
    
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getCountry() {
        return country;
    }
    public  void setCountry(String country) {
        this.country = country;
    }
    public int getLatestTotalCases() {
        return latestTotalCases;
    }
    public void setLatestTotalCases(int latestTotalCases) {
        this.latestTotalCases = latestTotalCases;
    }
    @Override
    public String toString() {
        return "LocationStats{" +
                "state='" + state + '\'' +
                ", country='" + country + '\'' +
                ", latestTotalCases=" + latestTotalCases +
                '}';
    }
    
}

//////////////////////// HomeController.java //////////////// //////

@RequestMapping("/")
public ModelAndView home() {    
    
    
    ModelAndView mv = new ModelAndView();
    mv.addObject("location", coronaVirusDataService.getAllStates());
    mv.setViewName("home.jsp");
    return (mv);        
}

//////////////// home.jsp ///////////////////

<table>
  <tr>
    <th>state</th>
    <th>country</th>
    <th>latestTotalCases</th>
  </tr>
   <tr th:each="elements : ${location}">
    <td th:text="${elements.state}"></td>
    <td th:text="${elements.country}"></td>
    <td th:text="${elements.latestTotalCases}">0</td>
  </tr>             
</table>  
<table>
  <tr>
    <th>state</th>
    <th>country</th>
    <th>latestTotalCases</th>
  </tr>
  <c:forEach items="${location}" var="element"> 
    <tr>
      <td>${element.state}</td>
      <td>${element.country}</td>
      <td>${element.latestTotalCases}</td>
    </tr>
  </c:forEach>
</table>

您應該在jsp文件的開頭添加taglib

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

比你可以這樣寫:

<table>
  <tr>
    <th>state</th>
    <th>country</th>
    <th>latestTotalCases</th>
  </tr>
    <c:forEach items="${location}" var="elements">
        <tr>
            <td>${elements.state}</td>
            <td>${elements.country}</td>
            <td>${elements.latestTotalCases}</td>
        </tr>
    </c:forEach>             
</table>  

您還可以檢查此“位置”是否不為空,例如通過打印出來:

<%=location%>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM