Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Laboratory work: 4

Learning Spring Boot and Thymeleaf


Prelab work

1- What is Thymeleaf?
Thymeleaf is a Java XML/XHTML/HTML5 Template Engine that can work both in web (Servlet-
based) and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer
of MVC-based web applications, but it can process any XML file even in offline environments. It
provides full Spring Framework integration.

The template file of Thymeleaf in essence are only a ordinary document file with the format
of XML/XHTML/HTML5. Thymeleaf Engine will read a template file and combine
with Java objects to generate another document.
Thymeleaf can be used to replace JSP on the View Layer of Web MVC application. Thymeleaf is
open source code software, licensed under the Apache 2.0.
Below is the image of the application that we will perform in this lesson:
2- Create application
On Eclipse/Intellij IIDEA select:

 File/New/Other...

Enter:
 Name: SpringBootThymeleaf
 Group: org.o7planning
 Artifact: SpringBootThymeleaf
 Description: Spring Boot and Thymeleaf
 Package: org.o7planning.thymeleaf

Select 2 Web and Thymeleaf technologies.


Your Project has been created:

pom.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 http://maven.apache.org/xsd/maven-4.0.0.xsd">
6 <modelVersion>4.0.0</modelVersion>
7
8 <groupId>org.o7planning</groupId>
9 <artifactId>SpringBootThymeleaf</artifactId>
10 <version>0.0.1-SNAPSHOT</version>
11 <packaging>jar</packaging>
12
13 <name>SpringBootThymeleaf</name>
14 <description>Spring Boot and Thymeleaf</description>
15
16 <parent>
17 <groupId>org.springframework.boot</groupId>
18 <artifactId>spring-boot-starter-parent</artifactId>
19 <version>2.0.0.RELEASE</version>
20 <relativePath/> <!-- lookup parent from repository -->
21 </parent>
22
23 <properties>
24 <project.build.sourceEncoding>UTF-
25 8</project.build.sourceEncoding>
26 <project.reporting.outputEncoding>UTF-
27 8</project.reporting.outputEncoding>
28 <java.version>1.8</java.version>
29 </properties>
30
31 <dependencies>
32 <dependency>
<groupId>org.springframework.boot</groupId>
33
<artifactId>spring-boot-starter-
34
thymeleaf</artifactId>
35
</dependency>
36
<dependency>
37
<groupId>org.springframework.boot</groupId>
38
<artifactId>spring-boot-starter-web</artifactId>
39
</dependency>
40
41
<dependency>
42
<groupId>org.springframework.boot</groupId>
43 <artifactId>spring-boot-starter-test</artifactId>
44 <scope>test</scope>
45 </dependency>
46 </dependencies>
47
48 <build>
49 <plugins>
50 <plugin>
51 <groupId>org.springframework.boot</groupId>
52
53 <artifactId>spring-boot-maven-
54 plugin</artifactId>
55 </plugin>
</plugins>
</build>

</project>

3- Thymeleaf Template
Thymeleaf Template is a template file. Its contents are in the XML/XHTML/HTML5 format. We
will create 3 files and place it in the src/main/resources/templates folder:

index.html
?
1 <!DOCTYPE HTML>
2 <html xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <meta charset="UTF-8" />
5 <title>Welcome</title>
6 <link rel="stylesheet" type="text/css"
7 th:href="@{/css/style.css}"/>
8 </head>
9 <body>
10 <h1>Welcome</h1>
11 <h2 th:utext="${message}">..!..</h2>
12
13 <!--
14
15 In Thymeleaf the equivalent of
16 JSP's ${pageContext.request.contextPath}/edit.html
17 would be @{/edit.html}
18
19 -->
20
21 <a th:href="@{/personList}">Person List</a>
22
23 </body>
24
25 </html>
personList.html
?
1 <!DOCTYPE HTML>
2 <html xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <meta charset="UTF-8" />
5 <title>Person List</title>
6 <link rel="stylesheet" type="text/css"
7 th:href="@{/css/style.css}"/>
8 </head>
9 <body>
10 <h1>Person List</h1>
11 <a href="addPerson">Add Person</a>
12 <br/><br/>
13 <div>
14 <table border="1">
15 <tr>
16 <th>First Name</th>
17 <th>Last Name</th>
18 </tr>
19 <tr th:each ="person : ${persons}">
20 <td th:utext="${person.firstName}">...</td>
21 <td th:utext="${person.lastName}">...</td>
22 </tr>
23 </table>
24 </div>
25 </body>
26 </html>
addPerson.html
?
1 <!DOCTYPE HTML>
2 <html xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <meta charset="UTF-8" />
5 <title>Add Person</title>
6 <link rel="stylesheet" type="text/css"
7 th:href="@{/css/style.css}"/>
8 </head>
9 <body>
10 <h1>Create a Person:</h1>
11
12 <!--
13 In Thymeleaf the equivalent of
14 JSP's ${pageContext.request.contextPath}/edit.html
15 would be @{/edit.html}
16 -->
17
18 <form th:action="@{/addPerson}"
19 th:object="${personForm}" method="POST">
20 First Name:
21 <input type="text" th:field="*{firstName}" />
22 <br/>
23 Last Name:
24 <input type="text" th:field="*{lastName}" />
25 <br/>
26 <input type="submit" value="Create" />
27 </form>
28
29 <br/>
30
31 <!-- Check if errorMessage is not null and not empty -->
32
33 <div th:if="${errorMessage}" th:utext="${errorMessage}"
34 style="color:red;font-style:italic;">
35 ...
36 </div>
37
38 </body>
</html>
I have created 3 HTML files above. The above HTML files need to be appropriate to the standards
of XML. All tags must have open and close, for example:
?
1 <div>A div tag</div>
2
3 <br />
4
5 <meta charset="UTF-8" />
All HTML files need declaring use of Thymeleaf Namespace:
?
1 <!-- Thymeleaf Namespace -->
2
3 <html xmlns:th="http://www.thymeleaf.org">
In template files, there are Thymeleaf Markers (markers of Thymeleaf) which are instructions
helping Thymeleaf Engine process data.
Thymeleaf Engine analyses template files and combines them with Java data to generate a new
document.
Below are examples to use the Context-Path in the Thymeleaf:
?
1
<!-- Example 1: -->
2
3
<a th:href="@{/mypath/abc.html}">A Link</a>
4
5
Output: ==>
6
7 <a href="/my-context-path/mypath/abc.html">A Link</a>
8
9
10 <!-- Example 2: -->
11
12 <form th:action="@{/mypath/abc.html}"
13 th:object="${personForm}" method="POST">
14
15 Output: ==>
16
17
<form action="/my-context-path/mypath/abc.html" method="POST">
18

4- Static Resource & Properties File


For Static Resources, for example, css, javascript, image files,.. you need to put them
into src/main/resources/static folder or its subfolders.
style.css
?
1 h1 {
2 color:#0000FF;
3 }
4
5 h2 {
6 color:#FF0000;
7 }
8
9 table {
10 border-collapse: collapse;
11 }
12
13 table th, table td {
14 padding: 5px;
15 }
application.properties
?
1 spring.thymeleaf.cache=false
2
3 welcome.message=Hello Thymeleaf
4 error.message=First Name & Last Name is required!

5- Model, Form, Controller classes


Person.java
?
1 package org.o7planning.thymeleaf.model;
2
3 public class Person {
4
5 private String firstName;
6 private String lastName;
7
8 public Person() {
9
10 }
11
12 public Person(String firstName, String lastName) {
13 this.firstName = firstName;
14 this.lastName = lastName;
15 }
16
17 public String getFirstName() {
18 return firstName;
19 }
20
21 public void setFirstName(String firstName) {
22 this.firstName = firstName;
23 }
24
25 public String getLastName() {
26 return lastName;
27 }
28
29 public void setLastName(String lastName) {
30 this.lastName = lastName;
31 }
32
33 }
PersonForm class represents for the data of FORM when you create a
new Person on addPerson page..
PersonForm.java
?
1 package org.o7planning.thymeleaf.form;
2
3
4 public class PersonForm {
5
6 private String firstName;
7 private String lastName;
8
9 public String getFirstName() {
10 return firstName;
11 }
12
13 public void setFirstName(String firstName) {
14 this.firstName = firstName;
15 }
16
17 public String getLastName() {
18 return lastName;
19 }
20
21 public void setLastName(String lastName) {
22 this.lastName = lastName;
23 }
24
25 }
MainController is a controller class. It processes a user's requests and controls the flow of the
application.
MainController.java
?
1 package org.o7planning.thymeleaf.controller;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.o7planning.thymeleaf.form.PersonForm;
7 import org.o7planning.thymeleaf.model.Person;
8 import org.springframework.beans.factory.annotation.Value;
9 import org.springframework.stereotype.Controller;
10 import org.springframework.ui.Model;
11 import org.springframework.web.bind.annotation.ModelAttribute;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestMethod;
14
15 @Controller
16 public class MainController {
17
18 private static List<Person> persons = new
19 ArrayList<Person>();
20
21 static {
22 persons.add(new Person("Bill", "Gates"));
23 persons.add(new Person("Steve", "Jobs"));
24 }
25
26 // Inject via application.properties
27 @Value("${welcome.message}")
28 private String message;
29
30 @Value("${error.message}")
31 private String errorMessage;
32
33 @RequestMapping(value = { "/", "/index" }, method =
34 RequestMethod.GET)
35 public String index(Model model) {
36
37 model.addAttribute("message", message);
38
39 return "index";
40 }
41
42 @RequestMapping(value = { "/personList" }, method =
43 RequestMethod.GET)
44 public String personList(Model model) {
45
46 model.addAttribute("persons", persons);
47
48 return "personList";
49 }
50
@RequestMapping(value = { "/addPerson" }, method =
51
RequestMethod.GET)
52
public String showAddPersonPage(Model model) {
53
54
PersonForm personForm = new PersonForm();
55
model.addAttribute("personForm", personForm);
56
57
return "addPerson";
58
}
59
60
@RequestMapping(value = { "/addPerson" }, method =
61
RequestMethod.POST)
62
public String savePerson(Model model, //
63
64 @ModelAttribute("personForm") PersonForm
65 personForm) {
66
67 String firstName = personForm.getFirstName();
68 String lastName = personForm.getLastName();
69
70 if (firstName != null && firstName.length() > 0 //
71 && lastName != null && lastName.length() > 0)
72 {
73 Person newPerson = new Person(firstName,
74 lastName);
75 persons.add(newPerson);
76
return "redirect:/personList";
}

model.addAttribute("errorMessage", errorMessage);
return "addPerson";
}

6- Run the application


To run the application, right click on Project and select:

 Run As/Spring Boot App.

The application has been deployed on an Embedded Web Server.


Run the following URL on the browser:

 http://localhost:8080/

You might also like