java—如何循环jstl中的对象列表

mznpcxlj  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(585)

在这里输入图像描述我有下面的列表,它来自一个类通过tostring方法。我将modelandview对象中的列表传递给jsp页面。现在我想循环这个列表并在jsp页面中创建一个表。请引导。

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

//////////////////////////位置统计.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 +
                '}';
    }

}

/////////////////////////////家庭控制器.java////////////////////////

@RequestMapping("/")
public ModelAndView home() {    

    ModelAndView mv = new ModelAndView();
    mv.addObject("location", coronaVirusDataService.getAllStates());
    mv.setViewName("home.jsp");
    return (mv);        
}

///////////////////主页.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>
uz75evzq

uz75evzq1#

你应该加上 taglib 年初 jsp 文件。

<%@ 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%>
ibrsph3r

ibrsph3r2#

<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>

相关问题