【问题标题】:Thymeleaf access field of classThymeleaf 访问类的字段
【发布时间】:2021-09-09 12:49:25
【问题描述】:

我有一个名为 A 的类,它有多个字段,另一个名为 B 的类有一个 A 类的对象。 th:object 的形式是 B 类 然后在 html 文件中,我想使用 thymeleaf 获取 th:field 中 A 类中的字段的输入 所以通常我会做th:field="*{field}",但该字段不在B类内它在A类内......那么我该怎么做th:field="{B.Aobj.field}"? 我试过了

【问题讨论】:

  • 反正我找到了办法。如果有人有更好的东西请告诉我!因此,我在控制器中创建了一个 A 类的对象 A_obj 和一个 B 类的对象 B_obj。然后我将 A_obj 设置为我的 B_obj 的属性。然后我将它们都添加到模型中。在 page.html 中,表单将 B_obj 作为对象。在输入中,我将使用 th:field="*{A_obj.field}" 调用 A_obj 的字段

标签: html spring spring-boot spring-mvc thymeleaf


【解决方案1】:

您不需要将 A 添加到模型中。您只需添加额外的点. 即可访问子对象的属性。例如,如果您的课程如下所示:

class Directions {
  private int miles;
  private Location source;
  private Location destination;

  // all the getters and setters
}

class Location {
  private String name;
  private String address;
  
  // all the getters and setters
}

您可以通过点遍历访问A 和B 的属性。

<form th:object="${directions}">
  <!-- properties of a -->
  <input type="text" th:field="*{miles}" />

  <!-- properties of b -->
  <input type="text" th:field="*{source.name}" />
  <input type="text" th:field="*{source.address}" />

  <input type="text" th:field="*{destination.name}" />
  <input type="text" th:field="*{destination.address}" />
</form>

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多