This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

If you’re a Java kid like me, I don’t recommend taking the time to learn Thymeleaf, but his ideas are worth learning. But its essence seems to me to be a clone of Jsp technology (Jsp is rarely used nowadays). The front-end can be directly used by the front-end frame Vue.

In my eyes, there is nothing I don’t want to learn right now. And testing, operation and maintenance, front-end everything to be able to point. In addition, the number of People learning Java is probably still the largest on the back end.

Free background template at the end of the article, we can directly download the demand.

I don’t think I would have written this article on a whim ๐Ÿ‘ฉ๐Ÿ’ป if it wasn’t for a school assignment.

Read this article at ๐Ÿ“–

  1. Learn Thymeleaf grammar ๐Ÿ„โ™€๏ธ
  2. Know how Thymeleaf integrates with SpringBoot ๐Ÿคนโ™€๏ธ
  3. Use Thymeleaf to complete school teacher assignments ๐Ÿ‘จ๐Ÿ”ฌ
  4. If there is a need, you can directly next template, combined with SpringBoot to write a graduation project ๐Ÿ‘จ๐Ÿ’ป

First, Thymeleaf introduction ๐Ÿ““

Thymeleaf website

Thymeleaf official documentation

Thymeleaf is a modern server-side Java templating engine for Web and standalone environments.

Thymeleaf’s primary goal is to bring elegant natural templates to your development workflow — HTML that displays correctly in a browser or works as a static prototype, enhancing collaboration among development teams.

With the Spring Framework’s modules, extensive integration with your favorite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern HTML5 JVM Web development — though it has more. — Official introduction

SpringBoot integration Thymeleaf ๐Ÿ“š

We’ll focus on some of the most common uses in our project. We’re also going to talk directly about the use of Thymeleaf in the project.

2.1. Create a SpringBoot project

This one goes without saying, I think everyone knows how to do this.

2.2. Import dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.2</version>
    <relativePath/>
</parent>   
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId> 
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
Copy the code

2.3 SpringBoot Directory for storing static resources

First we download the template:

Click doc, copy the required page files into the Resources/Templates package, and copy CSS, images, and JS into the Resources /static package.

2.4. Write the configuration file

Thymeleaf can be configured with some properties, this is just common ha.

spring:
  thymeleaf:
    enabled: true  # Enable thymeleaf view parsing
    encoding: utf-8  # code
    prefix: classpath:/templates/  The # prefix is also the default and can be left unconfigured
    cache: false  # Whether to use cache
    mode: HTML  # Strict HTML syntax pattern
    suffix: .html  # suffix
Copy the code

2.5. Write controllers

Let’s take the login page as an example and write a Controller to jump to login.html.

@Controller
@RequestMapping
public class LoginController {

    /** * Jumps to the login page */
    @GetMapping("/login")
    public String login(a){
        return "login";
    }

    /** * simulate login request */
    @PostMapping("/doLogin")
    public String doLogin(String username,String password){
        if(username! =null&&password! =null){
            System.out.println(username+password);
            // Redirecting requests to /indedx can also redirect pages
            return "redirect:/index";
        }
        return "login";
    }

    /** * jump to the index page */
    @GetMapping("/index")
    public String index(a){
        return "index"; }}Copy the code

2.6 Start projects & problem solving

There is nothing to change in the boot class, just run.

After starting the project, access localhost:8080/login and you may see a page that is missing CSS and JS. Not the successful page below.

After making the changes, you should also make some changes in the header of the HTML page:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
Copy the code

2.7 Thyemleaf is commonly used

Thymeleaf official website quick introduction

Thymeleaf official documentation

2.7.1, th: href | link (URL) expression

In fact, we just said this:

/ / before<link rel="stylesheet" type="text/css" href="/css/main.css">// Modified:<link rel="stylesheet" type="text/css" th:href="@{/css/main.css}">
Copy the code

The reason for doing this is due to Thymeleaf’s grammatical rules.

Examples of errors:

<link rel="stylesheet" type="text/css" th:href="@{/static/css/main.css}">
Copy the code

The imported resource path must not be prefixed with the path in the set of static resource paths. Otherwise, the resource cannot be requested.

After we use Thymeleaf’s @{} modifier, it will look for itself under the static package.

Note: Prior to SpringBoot 2.0 interceptors did not block static resources by default, but after SpringBoot 2.0 interceptors will block everything, so you need to override the addInterceptors method to release either your own static resources or those in WebJars

Of course, I’m just saying that this article does not cover interceptors.

2.7.2, th: text

We all need a prompt once in a while. Simply display a piece of text like this:

<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
Copy the code

Let’s modify the previous Controller:

/*** Jumps to the login page */
@GetMapping("/login")
public String login(Model model){
    model.addAttribute("systemName".Student Management System);
    return "login";
}
Copy the code

Also modify the login page:

<div class="logo">
    <h1 th:text="${systemName}"></h1>
</div>
Copy the code

2.7.3, th: action

Form submission I think is the most common.

<form class="login-form" method="post" th:action="@{/doLogin}">
</form>
Copy the code

The path submitted here also needs to be wrapped with @{}.

The back end is the same as it is.

2.7.4, th:each & th:if

Loop, judgment should be where can not use it.

Student class, we’ll use it later

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Long id;
    private String name;
    private Integer age;
    /** * true for male * false for female */
    private Boolean gender;
}

Copy the code

Write a controller

/** * Add multiple students */
@GetMapping("/doEach")
public String doEach(Model model){
    List<Student> students = new ArrayList<>();
    Student student1 = new Student(1L.Student Number one.20.true);
    students.add(student1);
    Student student2 = new Student(2L.Student Number two.21.true);
    students.add(student2);
    Student student3 = new Student(3L.Student Number three.22.false);
    students.add(student3);
    Student student4 = new Student(4L.Student Number four.23.true);
    students.add(student4);
    model.addAttribute("students",students);
    return "each";
}
Copy the code

Write another page, each. HTML

<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>The for loop</title>
</head>
<body>

<table border="1">
    <tr>
        <th>id</th>
        <th>The name</th>
        <th>age</th>
        <th>gender</th>
    </tr>
    <tr  th:each="student : ${students}" >
        <td th:text="${student.id}"></td>
        <td th:text="${student.name}"></td>
        <td th:text="${student.age}"></td>
<! -- ternary expression -->
        <td th:text="${student.gender}? Male: female"></td>
        <td th:if="${student.gender}">Use if to determine the gender of male</td>
        <td th:if="${not student.gender}">Use "if" to determine gender</td>
    </tr>
</table>
</body>
</html>
Copy the code

Results:

2.8, summary

I just briefly mentioned Thymeleaf, it supports a lot of things, not one by one in this, if there is a need, you can directly query the Thymeleaf documentation.

Free background template ๐Ÿ“‹

1. Free background template: Vail Admin

2, gather multiple free background templates: free templates

Just click on it and download it. Just reference it in the SpringBoot project.

Four, talk to yourself ๐Ÿš€

Hello, THIS is blogger Ning Zaichun: homepage

I hope you found this article useful!!

Wish us: by the time we meet on another day, we have achieved something.

Welcome to discuss the question ๐Ÿ˜, lie down ๐Ÿ›Œ

Don’t miss it. Leave a comment below for a chance to get some nuggets nuggets gifts.

The more you comment, the more likely you are to win an award!!

Details ๐Ÿ‘‰ Diggin project