我将对象添加到 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/