Show table of data using Spring boot and ThymeLeaf

Problem

Building a web application in Java that will be showing a table of data in the frontend, be that web browser on a Desktop, laptop or mobile phone.

Solution

Spring framework comes to the rescue. It will help us to build the server that will be offering APIs, or simply HTTP requests and responding with some information. For displaying information Spring offers few options. For instance, JSP – Java Server Pages, Apache Freemarker and some others. Thymeleaf is used as the view technology for this tutorial.

Analysis

So the ready web application will be a server that will be serving a list of students shown nicely in a table. The list of students are hardcoded for simplicity, they could have been sourced from a database.

In Spring world, there is the Spring Initializr that speeds up things by creating the project with its needed dependencies.

For this tutorial we will need only two dependencies

Also Maven is used in this case for dependency management with Java 8.

Generate the project and import it to an IDE, for instance Spring Tool Suite

The downloaded file when extracted has the following structure:

Create a Java Controller to accept GET requests as follows:

package com.programmerabroad.tabledata;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class StudentController {

    @GetMapping("/")
    public String showStudents(Model model) {

            List<String> students = new ArrayList<>();

            students.add("Isaac Newton");
            students.add("Leonardo Da Vici");
            students.add("Albert Einstein");

            model.addAttribute("students", students);

            return "students";
    }
}

The controller above is returning “students” as String. Because we added Thymeleaf in the dependencies, Spring will go and look for an HTML file called “students” + .html inside the templates directory (i.e. templates/students.html). That’s simply by design of the framework.

The students.html file will show the students in a table. The code is as follows:

(sorry WordPress plugin failed)

Output:

This is the output in the web browser with the green appearing when the mouse is moved over a row.

Conclusion

In this tutorial we saw how to quickly set up a web application using Spring framework, use Thymeleaf as view technology and show a list of data on the frontend. Thyemeleaf has lots of tags that can be useful when designing the frontend, you can check them out on their official site.


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x