2017-03-23 81 views
0

在Java/springboot的代码:打印键/从散列映射thymeleaf值/数组列表

@RequestMapping(value = "results") 
public String results(
     Model model, 
     @RequestParam String searchType, 
     @RequestParam String searchTerm) { 

    model.addAttribute("columns", ListController.columnChoices); 
    ArrayList<HashMap<String, String>> jobsbyval = JobData 
      .findforValue(searchTerm); 
    model.addAttribute("items", jobsbyval); 
    return "search"; 
} 

在HTML/thymeleaf的代码:

<div> 
    <table> 
    <tbody> 
     <tr th:each="item : ${items}"> 
     <!--each loop begins --> 
     <td th:text="${item}"></td> //item.value or item.key dont work!! 

     </tr> 
     <!--loop ends --> 
    </tbody> 
    </table> 
</div> 

下面是HTML输出中。

{header 1=something, header 2=Analyst, category 3=somename, location=somewhere, skill=Stats} 

将所需的HTML输出(键/值),以表格形式将是:

header 1 something 
header 2 Analyst 
category somename 
location somewhere 
skill Stats 
+0

非常感谢您编辑代码并输出整齐。我在编辑器中尝试过无数次,但没有成功。再次感谢你!! – aguy01

回答

2

是的,这是行不通的,因为items(或jobsbyval)不是地图,但它是一个列表的地图,即:ArrayList<HashMap<String, String>> jobsbyval

您的thymeleaf片段只会列出列表中第一个和唯一映射的字符串表示形式。如果您需要遍历你需要嵌套循环列表中的所有地图,例如:

型号

List<Map<String, String>> mapsList = new ArrayList<Map<String, String>>(); 

    Map<String, String> map1 = new HashMap<String, String>(); 
    map1.put("keyinmap1", "valueinmap1"); 
    Map<String, String> map2 = new HashMap<String, String>(); 
    map2.put("keyinmap2", "valueinmap2"); 

    mapsList.add(map1); 
    mapsList.add(map2); 

    modelMap.put("mapsList", mapsList); 

查看

<div th:each="map : ${mapsList}"> 
    <div th:each="mapEntry : ${map}"> 
     <span th:text="${mapEntry.key}"></span> = 
     <span th:text="${mapEntry.value}"></span> 
    </div> 
</div> 

输出

keyinmap1 = valueinmap1 
keyinmap2 = valueinmap2 

th:each接受的地图,在这种情况下:

当迭代地图,ITER变量将是一流的 java.util.Map.Entry

详情 - 见here