Spring Boot Templating in Baby Steps 🚀

Learn how to connect Java with HTML using Thymeleaf in the simplest way possible.

What is templating?

Templating means Java sends data and HTML displays it dynamically.

Controller → Model → Template → Browser

Step 1: Add Thymeleaf

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Step 2: Create template

src/main/resources/templates/index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
  <h1>Hello Template</h1>
</body>
</html>

Step 3: Controller

@Controller
public class PageController {

  @GetMapping("/")
  public String home() {
    return "index";
  }
}

Step 4: Dynamic data

model.addAttribute("name","Champak");
<h1>Hello <span th:text="${name}">User</span></h1>

Step 5: URL input

@GetMapping("/hello")
public String hello(@RequestParam String name, Model model){
  model.addAttribute("name",name);
  return "hello";
}

Step 6: Loop

<li th:each="t : ${topics}" th:text="${t}"></li>

Step 7: Condition

<p th:if="${name=='Champak'}">Welcome!</p>

Step 8: Fragment

<div th:replace="fragments/header :: header"></div>

Step 9: Static files

src/main/resources/static/css/style.css
<link rel="stylesheet" th:href="@{/css/style.css}">

@Controller vs @RestController

@Controller → HTML page
@RestController → API/data

Common mistake

Do not map two controllers to the same URL like /.

Final Summary

Controller → Model → Template → Browser
Read Again Share LinkedIn