2017-04-23 52 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的完整路径。