gpt4 book ai didi

java - Thymeleaf 显示 HashMap

转载 作者:行者123 更新时间:2023-12-02 08:03:30 25 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但我仍然找不到答案。

我的 Spring Boot 应用程序看起来像这样:

型号:

public class Company {

public static final String URL_COMPANY = "http://193.142.112.220:8337/companyList";
private Long iD;
private String companyName;
public static Map<Long, Object> companyMap;

public Long getiD() {
return iD;
}

public void setiD(Long iD) {
this.iD = iD;
}

public String getCompanyName() {
return companyName;
}

public void setCompanyName(String companyName) {
this.companyName = companyName;
}

@Override
public String toString() {
return companyName;
}}

Controller :

@Controller

public class UrlController {

@GetMapping("/success")
public String show(Model model) {

HashMap<Long, Object> company = (HashMap<Long, Object>) Company.companyMap;
model.addAttribute("companyID", company);
return "success";
}

查看:

<h1>All Companies:</h1>

<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="mapEntry: ${companyID}">
<td th:text="${mapEntry.key}"></td>
<td th:text="${mapEntry.value}"></td>

</tr>
</table>
<a th:href="@{/}">Homepage</a>
</body>
</html>

所以我的目标是显示一个包含公司 ID 和名称的表格。即使我的模型获得了 map ,我仍然无法在浏览器中看到它。表是空的。

    </tr>
<tr th:each="mapEntry: {1=Tire Systems, 2=IT Enterprise, 3=Car Manufacture, 4=Electro Market}">
<td th:text=""></td>
<td th:text=""></td>

</tr>

这是我检查页面源代码时得到的结果。所以我清楚地看到,该 map 已加载,但未显示。

此外,带有“主页”的链接不起作用,我不知道为什么?

我错过了什么?我正在尝试用公司填充表格,然后使用这些公司的 ID,通过此 ID 显示附加到公司的 Material 。我可以在表中使用 Id 的超链接吗?

最佳答案

所以你想显示一张 map 。如果您的 map 的值是 POJO 尝试类似以下内容

<tr><th>ID</th><th>Name</th></tr>
<tr th:each="mapEntry : ${companyID}">
<td th:text="${mapEntry.key}">keyvalue</td>
<td th:each="item : ${mapEntry.value}" th:text="${item.FIELD_NAME_OF_YOUR_POJO}">keyvalue</td>
</tr>

这应该有效。我试图展示的是,这是可能的。迭代取决于您的数据结构。如果有复杂的数据结构迭代也会相应改变。

如果您的映射的值是原始类型或 java 引用类型,您当前的代码应该可以工作。我已经执行了与您类似的代码,并且没有任何问题。请看一下 -

 HashMap<Long, Object> company = new HashMap<>();
company.put(1L, "Hello World");
model.addAttribute("companyID", company);

如果您的 map 的值是自定义 java 类型。然后按照前面的片段进行操作。

关于java - Thymeleaf 显示 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45490979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com