java - 使用 Thymeleaf 在 EL 表达式中进行类型转换

标签 java type-conversion el type-erasure thymeleaf

如何在 EL 表达式中转换对象类型? Thymeleaf 引擎似乎不理解这样的事情:

<span th:text="${((NewObjectType)obj).amount"></span>

谢谢。

更新:

我在其中存储数据的类层次结构。它们用于填充 HTML 表。

public class RootBase implements Serializable {
    ...
}

public class ColBase<T extends RootBase> implements Serializable {

    private ArrayList<T> internalList;

    public int getSize() {
       ...
    }

    public T get(int index) {
       return internalList(index);
    }
}

public class Row extends RootBase {
    ...
}

public class Rows extends ColBase<Row> {
    ...
}

Controller :

Rows rowsColObj = xxxJaxProxyService.getRows();
model.addAttribute("rows", rowsColObj);

查看:

<table style="width:100%; border:solid 1px" th:if="${statement}">
  <thead>
    <tr>
      <th style="text-align: left">#</th>
      <th style="text-align: left">Amount</th>
    </tr>
  </thead>
  <tbody th:object="${rows}">
    <tr th:each="index : *{#numbers.sequence(0, size - 1)}" th:with="entry=${#object.get(index)}">
      <td th:text="${index} + 1">1</td>
      <td th:text="${entry.amount}">0</td>
    </tr>
  </tbody>
</table>

最佳答案

您可以将列表包装在您自己的模型中吗? SpringMVC 和 Thymeleaf 的部分值(value)主张是将应用程序逻辑从 View 层中删除。转换是应用程序逻辑,应该在 Controller 中完成,或者如果必须的话......模型中完成。所以如果可能看起来像这样:

/**
 * Custom model for attributes displayed on the page.
 */    
MyPageModel
    List<TableRows> tableRows;
    public List<TableRows> getTableRows(){...}
    ...

接下来,在 Controller 方法中添加模型。以下是如何在模板中使用它来将模型绑定(bind)到 html 表:

<table>
    <tr th:each="tableRow : ${model.tableRows}">
        <td class="date" th:text="${tableRow.amount}">$103</td>
    </tr>
    <tr th:unless="*{tableRow}">
        <td colspan="3">No amounts available</td>
    </tr>
</table>

关于java - 使用 Thymeleaf 在 EL 表达式中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707961/

相关文章:

c - 为什么 MISRA-C 在某些情况下不允许隐式扩大类型?

grails - 在标记的属性内使用scriptlet或EL(Grails UI插件)

java - Android 的 RTP 库是否支持多播?

asp.net-mvc - 在 databasefirst mvc 中使用枚举作为下拉列表

oop - 转换代码应该属于哪个类?

jsf - EL中用于动态ResourceBundle键的字符串连接

java - 在 EL 中使用变量使用变量值

java - 如何让JScrollPane不隐藏JTable?

java - 写入 PDF 文档后使用 iText 打开它们

java - Spring MVC @RequestBody 用于 JAXB 域对象 接收到的 XML 的 XSLT 转换后