Spring-boot Project – Part 3: Thymeleaf

Thymeleaf.

From this point on, let’s start building the simplest form of controller class with Java.

This time, let’s start building a controller that calls index.html.

First, create a package called “controller” below src/main/java, and create a new class HelloWorldController.java.

Here’s the code.

In the Java code, value = “/” indicates the URL.

And “message” is embedded into index.html’s corresponding part.

HelloWorldController.java.

package com.dreams.budget_trakcer_project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWorldController {
	@RequestMapping(value = "/", method = RequestMethod.GET)
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!!");
        return "index";
    }
}

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Print Hello World</h1>
    <h2><span th:text="${message}"></span></h2>
  </body>
</html>

When you run the project, you can see this on your browser.

Leave a Reply