java - 如何从传递给 Thymeleaf 的模型中调用 getters 之类的参数?

标签 java spring spring-mvc thymeleaf

我将对象添加到 ModelAndView

ModelAndView model = new ModelAndView("index");
User currentUser = getUser();
model.addObject("currentUser", currentUser);

用户模型:

public class User {
    private String msisdn;
    private double balance;
    private double trafficResidue;
    private Map<String, String> variables;

    public String getMsisdn() {
        return msisdn;
    }

    public void setMsisdn(String msisdn) {
        this.msisdn = msisdn;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getTrafficResidue() {
        return trafficResidue;
    }

    public void setTrafficResidue(double trafficResidue) {
        this.trafficResidue = trafficResidue;
    }

    public Map<String, String> getVariables() {
        return variables;
    }

    public void setVariables(Map<String, String> variables) {
        this.variables = variables;
    }
}

我需要在 Thymeleaf 中调用 getter

我试过了

<label th:text="${currentUser.getMsisdn()}"/>

但它不起作用。如何从传递给 Thymeleaf 的模型中调用 getter,如参数?

最佳答案

如果您有一个标准的 getter 方法(采用 Thymeleaf 预期的格式),那么您可以只提及 objectName.fieldName 而不是 objectName.getFieldName(),尽管两者都可以。如果您的 getter 方法有一些非标准名称,那么 objectName.fieldName 将不起作用,您必须使用 objectName.yourweirdGetterMethodName()。

在您的情况下,对于字段 msisdn,您有一个标准的 getter 方法 getMsisdn()。所以,<label th:text="${currentUser.msisdn}"/><label th:text="${currentUser.getMsisdn()}"/>应该适合你。

再次, <label th:text="${currentUser.msisdn}"/>将工作得很好,您不必明确提及 getter 方法(因为它是标准的 getter 方法)。

不幸的是,这两个选项都不适合您。所以这基本上意味着,问题出在其他地方。我怀疑您添加到 View 中的对象。如果您可以发布 Controller 代码,我也许可以帮助您。

关于java - 如何从传递给 Thymeleaf 的模型中调用 getters 之类的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39865482/

相关文章:

java - 从文本文件中提取的数据存储在变量中时出现错误

java - 在 Java 中实例化一个新对象会重置该对象其他实例中的所有数据

java - 哈夫曼压缩文件(得到树但无法压缩)- Java

java - 为什么 addSeparator() 不适用于我的 JToolBar?

java.lang.AssertionError : Content type not set

java - 运行 spring boot build : Error creating bean with name 'entityManagerFactory' defined in class path

java - SpringMVC : how to get the value of @RequestMapping in the function

java - Struts 1 ActionForm - 从纯 HTML 中检索集合

java - Spring MVC 响应体

java - 匹配的通配符是严格的,但找不到元素 'resources' 的声明