how display in Thymeleaf List<Entity>

hello I would like to display a list of message and date but don't know how, I already find some code (Model and Themeleaf) but I can't change it properly :> my code: Service

@Autowired
private SpittleRepository spittleRepository;

private List<Spittle> spittles = new ArrayList<>(Arrays.asList(
        new Spittle("aaaa", new Date()),
        new Spittle("bbbbbb", new Date())
));

public List<Spittle> findSpittles() {
     List<Spittle> spittles = new ArrayList<>();
     spittleRepository.findAll().forEach(findedSpittles::add);
     return findedSpittles;
}}

Controller

@Autowired
SpittleService spittleService;

@RequestMapping(method = RequestMethod.GET)
public String findSpittles(Model model) {
    model.addAttribute("spittle", spittleService.findSpittles());
    return "spittles";
} }

Entity

        @Id
        private final Long id;
        private final String message;
        private final Date time;
        private Double latitude;
        private Double longitude;



        public Spittle(String message, Date time, Double latitude, Double 
        longitude) {
            this.id = null;
            this.message = message;
            this.time = time;
            this.latitude = latitude;
            this.longitude = longitude;
        }

        public Spittle(String message, Date time) {
            this(message, time, null, null);
        }

        + geters
}}

Thymeleaf

<h2>Lista spiltów</h2>
       <table class="table table-striped">
           <tr>
               <th>Message</th>
               <th>Date</th>
           </tr>
           <tr th:each="spittle : ${spittle}">
               <td th:text="${spittle.getMessage()}"></td>
               <td th:text="${spittle.getTime()}"></td>
           </tr>
       </table>

Repository don't have any code inside just extend JpaRepository

2 answers

  • answered 2018-03-13 21:19 want2learn

    Try

             <tr th:each="spittle : ${spittles}">
                   <td th:text="${spittle.message}"></td>
                   <td th:text="${spittle.time}"></td>
               </tr>
    

    You might need to use date.format for formatting your date.

  • answered 2018-03-14 09:04 tharanga-dinesh

    Try this changes,

    Controller

    @Autowired
    SpittleService spittleService;
    
    @RequestMapping(method = RequestMethod.GET)
    public List<Spittle> findSpittles(Model model) {
        model.addAttribute("spittles", spittleService.findSpittles());
        return "spittles";
    } }
    

    Service

    public List<Spittle> findSpittles() {
         List<Spittle> spittles = new ArrayList<>();
         spittles = spittleRepository.findAll().forEach(findedSpittles::add);
         return spittles;
    }}
    

    HTML

    <tr th:each="spittle : ${spittles}">
      <td th:text="${spittle.message}"></td>
      <td th:text="${spittle.time}"></td>
    </tr>