如何迭代春季百里香中的对象列表

时间:2019-06-20 12:53:39

标签: java spring thymeleaf

public class Members { 
    private String fname; 
    private String lname; 

    public String getFname() { 
        return fname; 
    } 

    public void setFname(String fname) { 
        this.fname = fname; 
    } 

    public String getLname() { 
        return lname; 
    } 

    public void setLname(String lname) { 
        this.lname = lname; 
    } 
} 

public class Greeting { 

    Map<String,List<Members>> templateMap; 

    public  Map<String, List<Members>> getTemplateMap() { 
        return templateMap; 
    } 
    public void setTemplateMap( Map<String, List<Members>> templateMap) { 
        this.templateMap = templateMap; 
    } 

} 

从上面的代码中,如何在html百里香的Spring thymeleaf中的 templateMap 中迭代和显示值?

1 个答案:

答案 0 :(得分:2)

在controller方法中,您必须像这样将其作为属性添加到模型中:model.addAttribute("map",getTemplateMap());(创建Greeting对象以从中获取templateMap)

然后在您的HTML中按如下方式进行访问:

<div th:each="stepEntry: ${map}"> // stepEntry now is each entry of your map. 
    <p th:text="${stepEntry.key}"></p> // this is the key value of the entry.
    <div th:each="member, iterStat : ${stepEntry.value}"> //this will iterate over the value (which is a list in this case) from the entry.
        <p th:text="${member.fname}"></p> //this prints the fname of each member in the list
    </div>
</div>