Displaying List of Objects in Table using Thymeleaf
3 CommentsLast Updated on May 11, 2019 by jt
A real common task is to display a list of objects fetched from the database in a HTML table on a webpage. Thymeleaf has a handy tag which allows us to iterate over a list of objects, and generate HTML code to display a table row for each object. The HTML generated really does not “need” to be a table row, but this a very common use case. Thymeleaf will simply generate the template code contained within the HTML div tags.
Typically, in your Spring MVC controller you will get a list of objects, and bind it to a property which is returned to the view layer. Ideally, your controller should be unaware of the source of the list. Often the source is ultimately a database access through a Spring service injected into the controller.
Free Introduction to Spring Tutorial
In the video example below, I show you how to get bind a list of Java objects to a property in the model returned to the Thymeleaf template engine. Then I show you how to iterate over the list to generate an HTML table. At the end of the demonstration, I run the example in Tomcat using Spring Boot and show you the HTML code generated by Thymeleaf.
Harpreet Dawar
excellent tutorial
Farhan
Excellent. But also provide source codes
mark
Scott, So this is cool but what about binding a Object and its properties to a dynamic number of rows in a POST situation.
Say I am implementing a Cart solution. I have a Payment object PaymentItem { reference: value, name: value, description: value, amount: value}. (I know this isn’t proper JSON but you should be able to get the gist of it).
Now in my page the number of rows in a table my be incremented dynamically. I’m trying to figure out how to bind using SpringBoot+Thymeleaf for each row’s Payment Item uniquely as a separate PaymentItem object in the collection so that I can submit them in the POST.
I used to be able to do this in Spring MVC + JSP using the ‘name’ and ‘path’ attributes but I’m having trouble identifying how to do this with SpringBoot+Thymeleaf.
Any suggestion or ideas?
thanks,
mark