从hashmap / arraylist

时间:2017-03-23 03:19:54

标签: arraylist hashmap thymeleaf

java / springboot中的代码:

@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

1 个答案:

答案 0 :(得分:4)

是的,它不起作用,因为items(或jobsbyval)不是地图,但它是地图列表,即:ArrayList<HashMap<String, String>> jobsbyval

您的百万美分片段只打印列表中第一个也是唯一一个地图的字符串表示。如果需要迭代列表中的所有映射,则需要嵌套循环,例如:

<强>模型

    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