Reputation: 2882
I add object to ModelAndView
ModelAndView model = new ModelAndView("index");
User currentUser = getUser();
model.addObject("currentUser", currentUser);
User model:
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;
}
}
And I need call getters in Thymeleaf
I tried
<label th:text="${currentUser.getMsisdn()}"/>
But it does not work. How can I call getters from model passed to Thymeleaf like parameter?
Upvotes: 8
Views: 8432
Reputation: 16465
If you have a standard getter method (in a format which Thymeleaf anticipates) then you can just mention objectName.fieldName instead of objectName.getFieldName(), though both will work. If your getter method has some non-standard name, then objectName.fieldName will not work, you have to use objectName.yourweirdGetterMethodName().
In your case, for the field msisdn, you have a standard getter method getMsisdn(). So, both <label th:text="${currentUser.msisdn}"/>
and <label th:text="${currentUser.getMsisdn()}"/>
should work just fine for you.
Again,
<label th:text="${currentUser.msisdn}"/>
will work just fine, you don't have to explicitly mention the getter method (since its a standard getter method).
Unfortunately, both this options doesn't work for you. So that essentially means, problem is somewhere else. I doubt the objects that you added ever made to the view. If you can post the controller code, I may be able to help you out.
Upvotes: 9
Reputation: 609
If you are just using the getter for the value you are use the attribute directly "${currentUser.msisdn}" Or if you want some logic to be added to getter and use it you can refer here: How to call object's method from Thymeleaf?
Upvotes: 0