[Java] Draw screen using Thymeleaf with SpringBoot

2 minute read

Purpose

Last time, I was able to display the character string on the browser using @RestController of Spring Boot, so This time, I’ll learn how to display an HTML file using @Controller.

Advance preparation

We will proceed assuming that a SpringBoot project already exists. For how to create a project, please refer to Spring Quickstart Guideandthisarticle is.

Let’s make #1.Controller! I think the source code when the Spring Quickstart Guide is over is as follows.

DemoApplication.java


package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}

With this implementation, delete unnecessary parts in DemoApplication.java file.

DemoApplication.java

``` completed form of java

package com.example.demo;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class DemoApplication {

public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }

}


Create a `controller` folder in the same hierarchy as DemoApplication.java.
Then, create `HelloController.java` in that folder and describe the process.



#### **`HelloController.java`**
```java

package com.example.demo.controller;

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

@Controller
public class HelloController {

@GetMapping("/hello")
public String hello(Model model) {
String message = "Hello World from HelloController!!!";
model.addAttribute("msg", message);
return "hello";
}
}

The annotation of HelloController class is @Controller. By using @Controller, it will return a template file written in html.

Since the part of return "○○" in the ○○ is the name of the html file, it means that hello.html must be created later.

Model sets the data to be used in the template. A message variable containing a character string is passed to the template using the format model.addAttribute("value name", value).

Controller is now complete!

2.Let’s use Thymeleaf!

I will create the View part of MVC, but this time use Thymeleaf.

Thymeleaf is a template engine that can be handled by springboot. The value stored in the variable on the Controller side can be displayed as an HTML file. [Thymeleaf Tutorial] written in Japanese (https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html#thymeleaf%E3%81%AE%E7%B4%B9%E4%BB%8B ) Is also available!

Now, edit the pom.xml file to use Thymeleaf.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>demo</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>11</java.version>
  </properties>

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

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
           <groupId>org.junit.vintage</groupId>
           <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- ↓↓↓↓↓ Added to use Thymeleaf ↓↓↓↓↓ -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

3.Create an HTML file for drawing the screen!

Let’s create hello.html in src/main/resources/templates.

The contents of hello.html are as follows. Don’t forget to define the thymeleaf namespace in the html tag!

hello.html


<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">

<head>
  <meta charset="UTF-8">
  <title>Spring Boot Lesson</title>
</head>

<body>
  <h1>Thymeleaf on Hello World!</h1>

  <h1 th:text="${msg}"></h1>
</body>

</html>

The value passed from the Controller is displayed by setting th:text="${msg}" in the second h1 tag.

4.Let’s run!

I have prepared to draw the HTML file with @Controller in 1~3 and draw the value defined in Controller using Thymeleaf. Let’s run it and check.

Enter the following command in the terminal and press Enter.

terminal: terminal$ ./mvnw spring-boot:run


After waiting for about 2 seconds, when you access http://localhost:8080/hello,

Screenshot 2020-07-01 10.45.40.png

hello.html is drawn, and the msg defined in Controller is also displayed correctly.

At the end

I learned how to display an HTML file using @Controller. There are many ways to write Thymeleaf, so I’ll write it on another occasion.

Reference site

Use “Thymeleaf” template with Spring Boot https://cloudear.jp/blog/?p=799

Tutorial: Using Thymeleaf (en) https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html#thymeleaf%E3%81%AE%E7%B4%B9%E4%BB%8B