Home > AI > Backend > SpringBoot > Thymeleaf >

intro

Step 1: install the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Step 2: Add the Controller class

GreetingController.java

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

Step 3: Add the greeting.html template

<!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" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

Step 4: Test result

GET http://localhost:8080/greeting?name=good
GET http://localhost:8080/greeting

Step 5: Error shooting

Circular View Path Error

If you have installed Thymeleaf, then you don’t neet to worry about this problem.

But if not, then you need to change the name of html template different with the REST API.

Leave a Reply