2017-04-23 50 views
0

有三類如何訪問與thymeleaf arraylist每個arraylist?

public Class Port{ 

private String portname; 
// with getters and setters 
} 

public Class Application{ 
private String appName; 
private List<Port> ports= new ArrayList<Port>(); 
// with getters and setters 
} 

public Class Service{ 
private String serviceName; 
private List<Application> apps= new ArrayList<Application>(); 
// with getters and setters 
} 

下面摘錄的是Thymeleaf HTML代碼可通過字段進行迭代的一部分。

<form action="#" th:action="@{/processWrapper}" th:object="${service}" method="post"> 
<table> 
<div th:each="app, stat : *{apps}"> 
<tr>     
<td><input type="text" th:field="*{apps[__${stat.index}__].appName}" th:name="|apps[${stat.index}]|" /></td> 
<div th:each="port, stat1 : *{app.ports}"> 
<td><input type="text" th:field="*{app.ports[__${stat1.index}__].portname}" th:name="|app.ports[${stat1.index}]|" /></td> 
    </div> 
    </div></table></form> 

爲什麼不工作我得到的錯誤信息:

屬性或字段「口」不能在類型「服務」的對象發現也許不公開?

+0

「服務」有一個名爲'ports'的屬性嗎?其次,你通常使用「公共」和「類」小寫。 – bphilipnyc

+0

服務沒有端口。服務只有應用程序的Arraylist,其中inturn有端口的數組列表。 代碼有正確的大小寫。我也更新了上述內容 – user757021

回答

1

你的HTML應該是這樣的:

<form action="#" th:action="@{/processWrapper}" th:object="${service}" method="post"> 
    <table> 
     <tr th:each="app, stat : *{apps}">     
      <td><input type="text" th:field="*{apps[__${stat.index}__].appName}" /></td> 
      <td th:each="port, stat1 : ${app.ports}"><input type="text" th:field="*{apps[__${stat.index}__].ports[__${stat1.index}__].portname}" /></td> 
     </tr> 
    </table> 
</form> 

至於什麼是錯的......

  1. 你並不需要所有這些額外的div秒。只需在tr s和td s自己上執行th:each即可。
  2. 當您使用th:field時,您不需要th:nameth:field生成name屬性。
  3. 此表達方式無效:*{app.ports[__${stat1.index}__].portname}
    • 首先,您不能在本地變量上使用*{}表達式。 *{app}無效 - 它試圖解析爲不存在的$ {service.app}。
    • 其次,當您構建th:field表達式時,必須構建整個路徑。修正後的表達式爲*{apps[__${stat.index}__].ports[__${stat1.index}__].portname},其中包括到portname的完整路徑。