In this tutorial we will learn how to create an application based on the Spring MVC pattern, and the Template engine Thymeleaf to render the page View.
Setting up the MVC Project
Out of the box, Spring Boot provides default configurations for Spring MVC. And when you bring a template engine into the project, you will also get all the view resolvers needed in order to move from standard JSP programming to modern template engines.
Let’s start from the Spring Boot Initializer, selecting as dependencies for your project “Web” and “Thymeleaf”. Download and extract the project to your hard drive.
Import the project in your favorite IDE and let’s start adding code to it!
This is the initial project structure:
src ├── main │ ├── java │ │ └── com │ │ └── example │ │ └── demo │ │ └── DemoApplication.java │ └── resources │ ├── application.properties │ ├── static │ └── templates └── test └── java └── com └── example └── demo └── DemoApplicationTests.java
Coding the View
Within the templates directory, I create a new HTML file named persons.html :
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Spring Boot Thymeleaf Hello World Example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>MasterSpringBoot</h1> <h2>Spring Boot Thymeleaf Hello World Example</h2> <table border="1" class="table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> <tr th:each="person : ${persons}"> <td th:text="${person.name}"></td> <td th:text="${person.surname}"></td> </tr> </tbody> </table> </body> </html>
As you can see from the above code, the first thing that I need to do to my HTML document is adding the XML namespace for Thymeleaf.
In the page we are displaying an HTML table, using an iterator to display all Person object loaded in the Model. In order to do that, we are using a th:each iterating over a list of persons from the model and create a new Person object. The magic is that Thymeleaf is able to resolve that for me as we go through.
Once completed the iteration over the persons, we need to populate the table cells using the th:text tag which references the Person object properties.
Coding the Model
Next step, will be adding a Person model object with the properties that we have already seen (name, surname) in the HTML:
package com.example.demo; public class Person { private String name; private String surname; public Person(String name, String surname) { super(); this.name = name; this.surname = surname; } public Person() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } }
Coding the Controller
Finally we need a Controller for our Person object so we will create a PersonController class:
package com.example.demo; 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; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Controller @RequestMapping("/persons") public class PersonController { private static List<Person> persons = new ArrayList(); static { Person p1 = new Person("Jack", "Smith"); Person p2 = new Person("Lucas", "Derrik"); Person p3 = new Person("Andy", "Miller"); persons.add(p1); persons.add(p2); persons.add(p3); } @GetMapping public String getAllPersons(Model model) { model.addAttribute("persons", persons); return "persons"; } }
We have annotated the class with @Controller, so that it can be component scanned. And we’re also we need a RequestMapping for it. Within this class, we need to add some sample data. To keep it simple, we will create statically of a list of Person.
Now, once that’s done, let’s create a GetMapping. We will return a public string called getAllPersons. And to the parameter of this method, we’re passing an object called Model, that is an Object from the org.spring framework UI package.
This object will be available in your view under the name “persons”. As you can see the method returns also “persons” which is simply the name of your view.
Running the application
Finally, we are able to run the application and request for http://localhost:8080/persons
Here ‘s the View that Thymeleaf produced:
Adding CSS and Javascript
To improve our example, we are going to add some static resources, such as CSS and Javascript. Firstly, you should place these resources under the resources/static folder as in the following directory tree:
src/main/resources/ ├── application.properties ├── static │ ├── css │ │ └── main.css │ └── js │ └── functions.js └── templates └── persons.html
So we have added the following resources:
- main.css – This is a stylesheet to customize the appearance of the View
- functions.js – This is a javascript file which contains a function we will trigger when the main page loads
Here is main.css:
h1{ color:#0000FF; } h2{ color:#FF0000; }
Finally, this is functions.js:
function hello() { alert("Hello from Spring MVC"); }
To include the above static resources, we will update the HEAD section of our HTML page as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Spring Boot Thymeleaf Hello World Example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link th:href="@{/css/main.css}" rel="stylesheet" /> <script type="text/javascript" th:src="@{/js/functions.js}"></script> </head> <body onload="hello()"> <!-- Unchanged --> </body> </html>
That’s it. Check again the persons.html page to see that changes are available:
Source code for this tutorial: https://github.com/fmarchioni/masterspringboot/tree/master/mvc/mvc-demo