如何在 Thymeleaf 中使用枚举作为方法参数?

问题描述 投票:0回答:1

我正在尝试调用一个方法,该方法将枚举作为 Thymeleaf 模板中的参数。枚举非常简单:

public enum Language {
  C,
  JAVA,
  DOTNET
}

调用的方法同样简单:

public int count(Language l) {
  return counter.get(l);
}

模板中的调用也很普通:

entry.value
指的是具有
DTO
方法的
count(Language)
对象:

<td th:text="${entry.value.count(T(com.sample.Language).C)}" />

但是当我尝试加载模板时,出现此错误:

EL1004E: Method call: Method count(com.sample.Language) cannot be found on type com.sample.DTO
。但是,如果我在
DTO
类中提供一个接受
String
的方法,然后将其转换为等效的
Language
枚举条目,那么一切都很好:

public int count(String lang) {
  return count(Language.valueOf(lang));
}

这似乎是矛盾的。一方面,错误文本表明 Thymeleaf 正在寻找带有

Language
参数的方法,但实际上它调用了带有
String
参数的方法。我的
String
对象中是否可能不需要
count
方法的
DTO
风格?

java enums thymeleaf
1个回答
0
投票

我对你的问题发表了评论并提出了建议,但找到了解决你问题的方法。

我阅读了https://www.thymeleaf.org/doc/articles/standarddialect5months.html中的文档,其中指出:

"<span th:text="${book.author.name}">

上面的表达式(在 OGNL 和 SpringEL 中)等价于:

((Book)context.getVariable("book")).getAuthor().getName()"

然后我尝试了:

context.setVariable("entry", YourDTOClass)

然后使用:

"${entry.count(@com.sample.Language@C)}"

得到了正确的结果

© www.soinside.com 2019 - 2024. All rights reserved.