Search code examples
javafreemarker

Freemarker : list of objects which contains other object


I want to print a list of objects which contains other object with the FreeMarker language

For example I have a Java object :

public class Adress
{
   private String _street;
   private String _city;
}

and another Java object :

public class House
{
     private int _nb_room;
     private Adress _adressHouse;
}

After I create a list with the data of my bdd :

public Collection<House> getHousesList()
{
   Collection<House> housesList = new ArrayList<House>();
   DAOUtil daoUtil = new DAOUtil( "SELECT nb_room, street, city FROM house", bdd);
   while(daoUtil.next())
   {
      House tmpHouse = new House();
      tmpHouse.setNbRoom(daoUtil.getString(1));

      Adress tmpAdress = new Adress();
      tmpAdress.setStreet(daoUtil.getString(2));
      tmpAdress.setStreet(daoUtil.getString(3));

      tmpHouse.setAdress(tmpAdress);
      housesList.add(tmpAdress);
   }
   daoUtil.free();
}

In another file I send the list to the html :

model.put('houseList',model.put('housesList',getHousesList());

And in my html I have :

<table>
   <#list houseList houseTmp>
      <tr>
         <td>${houseTmp.nb_room!''}</td>
         <td>${houseTmp.adressHouse.street!''}</td>
         <td>${houseTmp.adressHouse.city!''}</td>
      </tr>
   </#list>
</table>

When I look at my HTML on my browser there is only the number of room who print but not the address but when I do a break point before send the list to the HTML there is address inside.

So how can I access to the address of the house?


Solution

  • You have a private Adress _adressHouse; in your House class.

    Freemarker will not look at that, but at the public getter you might have.

    If you have getAdressHouse(), use ${houseTmp.adressHouse.street!''}. If you have getAdress(), use ${houseTmp.adress.street!''}.

    I'm guessing it is the second case, as you declared tmpHouse.setAdress(tmpAdress);