Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - Thymeleaf with Example

Thymeleaf is a modern server-side Java template engine suitable for both web and standalone environments. It's often used with Spring Boot because it integrates neatly with Spring's web MVC framework, allowing you to build dynamic web pages using natural templating techniques (i.e., you can open a Thymeleaf template with your browser and view it just like you would with a regular static HTML file).

Here's a simple example of how to set up a Spring Boot application with Thymeleaf:

1. Create a New Spring Boot Project

Use the Spring Initializr tool (https://start.spring.io/) or your favorite IDE to create a new Spring Boot project.

2. Add Dependencies

In the pom.xml file, add the following dependencies:

<dependencies>
    <!-- Spring Boot Web Starter (MVC, Tomcat) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Thymeleaf Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

3. Create a Thymeleaf Template

Inside src/main/resources/templates, create an HTML file named greeting.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Greeting Page</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'">Hello, World!</h1>
</body>
</html>

4. Create a Controller

Now, let's create a simple controller that will handle our request and provide a model attribute for the Thymeleaf template:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @GetMapping("/greet")
    public String greet(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting"; // This refers to the "greeting.html" template
    }
}

5. Run the Application

Start the application using your IDE or from the command line:

mvn spring-boot:run

6. Access the Greeting Page

Navigate to http://localhost:8080/greet in your browser. You should see "Hello, World!". If you navigate to http://localhost:8080/greet?name=John, you'll see "Hello, John!".

That's it! This basic setup allows you to create dynamic web pages using Thymeleaf and Spring Boot. You can expand on this foundation by exploring Thymeleaf's rich syntax for expressions, conditional rendering, loops, and more.

  1. Introduction to Thymeleaf in Spring Boot:

    • Description: Thymeleaf is a templating engine that simplifies the process of creating dynamic web pages in Spring Boot applications. It allows embedding dynamic content directly into HTML templates.
    • Code:
      <!-- Example Thymeleaf template -->
      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>Hello Thymeleaf</title>
      </head>
      <body>
          <h1 th:text="${message}">Default Message</h1>
      </body>
      </html>
      
  2. Configuring Thymeleaf with Spring Boot:

    • Description: Spring Boot automatically configures Thymeleaf when the necessary dependencies are included. Additional configuration can be done in application.properties or application.yml.
    • Code:
      # application.yml
      spring:
        thymeleaf:
          prefix: classpath:/templates/
          suffix: .html
          cache: false
      
  3. Thymeleaf templates and expressions in Spring Boot:

    • Description: Thymeleaf templates are HTML files with embedded Thymeleaf expressions. Expressions are used to render dynamic content.
    • Code:
      <!-- Thymeleaf template with expressions -->
      <h1 th:text="${greeting}">Default Greeting</h1>
      
  4. Model attributes and variables in Thymeleaf with Spring Boot:

    • Description: Pass data from Spring MVC controllers to Thymeleaf templates using model attributes. Access these attributes in templates.
    • Code:
      @Controller
      public class MyController {
          @GetMapping("/hello")
          public String hello(Model model) {
              model.addAttribute("greeting", "Hello, Thymeleaf!");
              return "hello";
          }
      }
      
  5. Layouts and fragments in Thymeleaf for Spring Boot:

    • Description: Create reusable layouts and fragments in Thymeleaf to structure your templates consistently.
    • Code:
      <!-- Layout template -->
      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>My Layout</title>
          <th:fragment name="head"></th:fragment>
      </head>
      <body>
          <div th:replace="fragments/header :: header"></div>
          <div th:replace="~{content}"></div>
          <div th:replace="fragments/footer :: footer"></div>
      </body>
      </html>
      
      <!-- Fragment templates (e.g., header and footer) -->
      
  6. Form handling and processing with Thymeleaf in Spring Boot:

    • Description: Thymeleaf simplifies form handling in Spring Boot. Use Thymeleaf attributes to bind form fields with model attributes.

    • Code:

      <!-- Form handling with Thymeleaf -->
      <form th:action="@{/submit}" th:object="${user}" method="post">
          <input type="text" th:field="*{username}" />
          <input type="password" th:field="*{password}" />
          <button type="submit">Submit</button>
      </form>
      
      @Controller
      public class FormController {
          @PostMapping("/submit")
          public String submitForm(@ModelAttribute User user) {
              // Process form submission
              return "result";
          }
      }
      
  7. Internationalization with Thymeleaf in Spring Boot:

    • Description: Thymeleaf supports internationalization (i18n). Use Thymeleaf's #{...} syntax for message keys.

    • Code:

      # messages.properties
      greeting.message=Hello, {0}!
      
      <!-- Thymeleaf template with internationalization -->
      <h1 th:text="#{greeting.message(${username})}">Default Greeting</h1>
      
  8. Thymeleaf integration with Spring Boot controllers:

    • Description: Spring Boot seamlessly integrates Thymeleaf with controllers. Model attributes are automatically available in Thymeleaf templates.
    • Code:
      @Controller
      public class MyController {
          @GetMapping("/hello")
          public String hello(Model model) {
              model.addAttribute("greeting", "Hello, Thymeleaf!");
              return "hello"; // Thymeleaf template name
          }
      }