Thymeleaf HashMap Display
This may be a stupid question, but I still cannot find an answer to it.
My Spring Boot App looks something like this:
Model:
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";
}
View:
<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>
So my goal is to display a table filled with ID and company names. Although my model is receiving the map, I still cannot see it in my browser. The table is empty.
</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>
This is what I get if I check the page source. So I can clearly see that the map is loaded but not displayed.
Also, the link to the "home page" doesn't work and I'm not sure why?
What am I missing? I am trying to populate a table with companies and then using the ID of those companies to show the materials attached to the company through that ID. Can I use hyperlinks in the table for Id?
source to share
So, you want to display the map. Your card's IF value is POJO. Try something like the following.
<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>
This should work. What I was trying to show is possible. The iteration depends on your data structure. If you have a complex data structure, the iteration will change accordingly.
If your map value is a primitive or Java reference type, your current code should work. I followed similar code as yours and it worked without too much trouble. Please take a look -
HashMap<Long, Object> company = new HashMap<>();
company.put(1L, "Hello World");
model.addAttribute("companyID", company);
If your map value is a custom java. Then follow the previous snippet.
source to share