Thymeleaf Templates

Spring web project with Thymealf and Spring Boot DevTools.
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Controller (not REST)

 
/**
 * Spring Boot MVC Controller
 * ********--
 * The Controller handle GET requests and returns the name
 * of View responsible to render html content.
 * 
 * Templates will not work in case that you have a @RestController
 * 
 * curl http://localhost:8080
 *      Hello Templates!
 * curl http://localhost:8080/message
 *      My message
 *  curl http://localhost:8080/hello
 *      Hello, guest!
 *  curl http://localhost:8080/hello?username=John
 *      Hello, John!
*/

package com.example;

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


@Controller
public class DemoTemplateController {
    
    @GetMapping("/")
    public String home() {
        return "index.html";
    }

    @GetMapping("/message")
    @ResponseBody
    public String message() {
        return "My message";  // just string
    }

    @GetMapping("/hello")
    public String hello(
        @RequestParam(name="username", required=false, defaultValue="guest") String str,
        Model model) {
        
        model.addAttribute("username", str);
        return "hello";  // .html can be omitted
    }
}

Template

resources/templates/hello.html
 
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>MyPage</title>
</head>
<body>
    <p th:text="'Hello, ' + ${username} + '!'">
</body>
</html>

Build and Run

 
mvn package
mvn spring-boot:run

curl http://localhost:8080/hello?username=John
    Hello, John!




References: