【问题标题】:How to access each arraylist within arraylist with thymeleaf?如何使用百里香访问arraylist中的每个arraylist?
【发布时间】:2017-09-19 22:51:08
【问题描述】:

一共有三个类

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
}

下面的 sn-p 是 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>

为什么它不起作用?我收到错误消息:

在“服务”类型的对象上找不到属性或字段“端口”可能不是公共的?

【问题讨论】:

  • Service 是否有一个名为ports 的属性?其次,您通常将publicclass 设为小写。
  • 服务没有端口。服务只有应用程序的 Arraylist,而应用程序又具有端口数组列表。代码有正确的大小写。我也更新了以上内容

标签: html spring-boot thymeleaf


【解决方案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. 您不需要所有这些额外的divs。只需在 trs 和 tds 上执行 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},其中包括端口名的整个路径。

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2015-06-07
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 2020-07-21
    • 2023-03-28
    • 1970-01-01
    • 2020-11-12
    相关资源
    最近更新 更多