Introduction of Spring Thymeleaf
1. IDE Environment Setup
a. Download Eclipse (https://www.eclipse.org/downloads/)
b. Download STS from Eclipse Marketplace (Help → Eclipse Marketplace → Search "STS" → Install)
2. Setup New Spring Project
a. Create New Project (If you are not able to see Spring Boot selection, it means that you have not installed STS plugin)
File → New → Other → Spring Starter Project → Next
b. Complete Below Configuration (Other fields using default)
Name: xxx (Ex. SpringThymeleaf)
Group: xxx.xxx (Ex. com.example)
Packaging: xxx.xxx (Ex. com.example)
→ Next
c. Select "Thymeleaf" under "Template Engines"
→ Finish
3. Add New Controller & HTML
a. Create a New Class under src/main/java named as HomeController.java
b. Insert below code in HomeController.java
package com.sample.controller; //Modify based on your package name
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HomeController { //!!Modify based on your Class Name
@RequestMapping("/home") //API Url
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name); //Using Thymeleaf method "{name}" to get value attribute
return "home"; //!!Return HTML View name
}
}
c. Create a New Folder "templates" under src/main/resources (Spring Boot default view folder)
d. Create a New HTML File in templates folder named as Home.html
e. Insert below code in Home.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/theme.css"></link>
<script type="text/javascript" src="js/myscripts.js"></script>
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
4. Run
a. Run the project with Spring Boot App
b. Access the page with url http://localhost:8080/home?name=James
By using Thymeleaf functionality in HTML are require to append below code
<html xmlns:th="http://www.thymeleaf.org" />
For more Thymeleaf plugin function may refer to this link Thymeleaf