[英]spring boot / thymeleaf nested loop object access
我正在使用Spring Boot和Thymeleaf為我的應用程序創建一個登陸頁面。 為此,我需要呈現一個都包含一個Container的Host對象的List。 以下是相關代碼:
public class Container {
private String name;
private String baseUrl;
private String status;
public Container(String name, String baseUrl, String status) {
this.name = name;
this.baseUrl = baseUrl;
this.status = status;
}
public String getName() { return name; }
public String getBaseUrl() { return baseUrl; }
public String getStatus() { return status; }
}
public class Host {
private HashMap<String, Container> containers;
....
public List<Container> getContainers() {
return containers.values();
}
}
@RequestMapping("/")
public class IndexController {
@RequestMapping("/")
public String getIndex(Model model) {
model.addAttribute("hosts", hostRepository.getAllServers());
return "index";
}
}
現在,我要遍歷所有服務器,並在表中顯示有關每個容器的信息。 我的Thymeleaf模板如下所示:
<div class="panel panel-default" th:each="host : ${hosts}">
<div class="panel-heading">
<b th:text="${host.name}">Host X</b>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr th:each="container : ${host.getContainers()}">
<!-- HERE IS THE PROBLEM -->
<td th:text="${container.name}">Service1</td>
<td th:text="${container.baseUrl}">domain.com/api/url</td>
<td th:text="${container.status}">RUNNING</td>
<!-- HERE ENDS THE PROBLEM -->
</tr>
</tbody>
</table>
</div>
</div>
</div>
我的問題是要訪問容器的屬性(由注釋標記)的部分。 每次我得到一個SpringEL Exception。 如果刪除th:text="${container.xy}"
並替換為th:text="${container}
,則會顯示該容器的字符串版本,因此我可以訪問該對象,並使該循環正常運行我還嘗試用getter(例如getStatus()
)替換字段訪問,但是它也不起作用。
謝謝你的幫助。 如果您需要更多信息,請隨時詢問。
設定:
編輯 :引發的異常是: nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "container.name" (index:35)
,其中index:35是有問題的第一行。
使用${container}
時,toString()的輸出為jenkins=com.my.app.Container@7552c269
而jenkins是Container實例的name
屬性。
解決方案似乎嵌套循環是在Map而不是List上進行迭代。 將${container.xy}
更改${container.xy}
${container.getValue().xy}
可解決此問題。
解
似乎嵌套循環正在org.thymeleaf.util.EvaluationUtil$MapEntry
而不是List上進行迭代。 將${container.xy}
更改${container.xy}
${container.getValue().xy}
可解決此問題。
一路學到的東西:
toString()
方法以獲得有關迭代對象的格式化信息。 在這種情況下,輸出為key=value
,這是預期的全部value
。 這提示當前對象必須是Container
實例以外的其他對象 getClass()
來檢查這里是否出錯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.