Search code examples
javaspringspring-mvcthymeleaf

How can I call getters from model passed to Thymeleaf like parameter?


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?


Solution

  • 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.