lundi 4 janvier 2021

How to loop over a list of object in JSTL

I have the following list which is coming from a class via toString method . I am passing the list in modelAndView object to jsp page. Now I want to loop over the list and make a table in jsp Page. Please guide.

 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>  



Aucun commentaire:

Enregistrer un commentaire