【问题标题】:Spring boot and thymeleaf: Can not evaluate size() of an ArrayListSpring Boot 和 thymeleaf:无法评估 ArrayList 的 size()
【发布时间】:2021-08-27 22:26:45
【问题描述】:

我的 mvc 控制器类中有一个 ArrayList:

List<Market> markets = loadMarkets();

我将此列表添加到模型对象:

model.addAttribute("markets", markets);

在我的模板中,当我想获取这个数组的 size() 时:

<span>Top <strong th:text="${markets.size}"></strong>assets.</span>

我收到了这个错误:

Cannot evaluate because of compilation error(s): The method size() is undefined for the type Object.

VSCode 调试工具截图:

我正在使用带有 Thymeleaf 模板引擎的 Spring Boot 版本 2.2.6.RELEASE。

【问题讨论】:

  • 根据您的错误消息,您有 Java 代码编译错误:``model.getAttribute("markets").size()` - 不是 Thymeleaf 表达式评估错误。您找不到Objectsize()(这是您从getAttribute() 方法返回的内容)。注释掉(或删除)那行 Java 代码,然后重试。看看你是否得到一个不同的错误 - 或者根本没有错误。
  • 这能回答你的问题吗? How to print Array size in thymeleaf? 注意说数组大小,但是关于数组列表。 thymeleaf 中有用于此的实用方法
  • 澄清一下:问题中的 Thymeleaf 表达式的工作方式如下:th:text="${markets.size}"。是的,有 Thymeleaf 实用程序对象——例如:th:text="${#lists.size(markets)}"——但我认为这里不需要。这是需要修复(或删除,如果不需要)的 Java 代码。
  • 是不是你使用size属性试图调用getSize(),但是没有这样的方法?我认为您需要像这样显式调用size() 方法:th:text="${markets.size()}"
  • 使用${markets.size()} 解决了这个问题。

标签: spring-boot thymeleaf spring-el


【解决方案1】:

当您使用属性表示法th:text="${markets.size}" 时,Thymeleaf 将在模型中的markets 属性上搜索方法getSize()。但是没有getSize()方法,只有size()方法。

所以使用方法本身而不是使用属性表示法:

th:text="${markets.size()}"

【讨论】:

  • 这让我大吃一惊。我有List&lt;Person&gt; people = ...,其中Person 是一个JavaBean。当我使用th:text="${people.size}" 时,我得到了预期的结果——并且没有错误。这是普通的 Thymeleaf(没有 Spring),以防万一。
  • 啊,我总是将 Thymeleaf 与 Spring 一起使用,所以可能确实存在差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 2019-02-26
相关资源
最近更新 更多