class 的 Thymeleaf 访问字段

Thymeleaf access field of class

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

您不需要将 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
}

您可以通过 dot-walking 访问 AB 的属性。

<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>