7、 Spring boot integrates thymeleaf template engine

lixingsikao 2021-04-08 10:26:59
spring boot integrates thymeleaf template

Preface : The last section is right SpringBoot Of Spring Boot Integrate Swagger2 Show online interface documentation Made an introduction , This section is mainly about Spring Boot Integrate Thymeleaf Template engine explanation and Analysis .

1. Thymeleaf Introduce

Thymeleaf Is applicable to Web And the modern server side of the stand-alone environment Java template engine .

Thymeleaf Of The main target Is to bring elegant nature to your development workflow Templates - Can be displayed correctly in the browser HTML, It can also be used as a static primitive type , So as to achieve more powerful collaboration in the development team .

The above is translated from Thymeleaf Official website . Conventional JSP+JSTL The combination is over ,Thymeleaf It is the template engine of modern server , With the traditional JSP Different ,Thymeleaf You can use your browser to type open , Because you can ignore the extension attribute , It's like opening a native page , It also brings some convenience to the front-end staff .

What does that mean ? That is to say, in the local environment or network environment ,Thymeleaf Can run . because thymeleaf Support html Prototype , Also support in html Add additional attributes to the tag to achieve “ Templates + data ” The way we show it , So artists can view the page effect directly in the browser , When the service starts , You can also make the back Platform developers view dynamic page effects with data . such as :

<div class="ui right aligned basic segment">
<div class="ui orange basic label" th:text="${blog.flag}"> Static original information </div>
<h2 class="ui center aligned header" th:text="${blog.title}"> This is a Static title </h2>

Similar to the above , On a static page , It shows static information , When the service starts , Dynamic access to the database After the data of , You can display dynamic data ,th:text Tags are used to dynamically replace text , This will be in the following section explain . This example shows how the browser interprets html Will ignore html Tag properties not defined in ( such as th:text), therefore thymeleaf Can be run statically ; When data is returned to the page , Thymeleaf Tags dynamically replace static content , Make the page dynamic display data .

2. Dependency import

stay Spring Boot Use in thymeleaf Templates need to introduce dependencies , You can check... When creating a project Thymeleaf, You can also create it and import it manually , as follows :

  • in addition , stay html If you want to use thymeleaf Templates , You need to introduce... In the page tag :

     <html xmlns:th="http://www.thymeleaf.org">

3. Thymeleaf Related configuration

because Thymeleaf There is already a default configuration in , We don't need to configure it too much , There is a need to Pay attention to ,Thymeleaf Page caching is on by default , So at the time of development , The page cache needs to be turned off , The configuration is as follows .

# Turn off caching 
cache: false

Otherwise, there will be a cache , The result is that the page can't see the updated effect in time . For example, if you modify a file , already update To tomcat 了 , But the refresh page is still the previous page , Because of Cache causes Of .

4. Thymeleaf Use

4.1 Visit static page

This and Thymeleaf Do not have what relation , It should be said that it is universal , The reason I'm writing it all here is that generally I When we do websites , You can make one 404 Page and 500 page , In order to give users a friendly display when something goes wrong , Instead of throwing out a bunch of abnormal information .Spring Boot The template directory is automatically identified in (templates/) Under the 404.html and 500.html file . We are templates/ Create a new one in the directory error Folder , specially The door is in the wrong place html page , Then print some information separately . With 404.html For example :

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
This is a 404 page

Let's write another controller Let's test it 404 and 500 page

public class ThymeleafController {
public String test404() {
return "index";
public String test500() {
int i = 1 / 0;
return "index";

  • When we type localhost:8080/thymeleaf/test400 when , Intentional input error , No corresponding method found , It will jump to 404.html Show .

  • When we type localhost:8080/thymeleaf/test505 when , It throws an exception , Then it will automatically jump to 500.html Show .

【 notes 】 Here's a problem to pay attention to , In the previous course, we said that there will be a separation between the front end and the back end in micro services , We are Controller All the layers are used @RestController annotation , Automatically converts the returned data into json Format . But when using the template engine ,Controller It doesn't work @RestController Note the , Because in use thymeleaf Template time , Returns the view file name , Like the one above Controller in It's going back to index.html page , If you use @RestController Words , Will be able to index As String Parsed , Back to the page , Instead of looking for index.html page , You can try . So when using templates @Controller annotation .

4.2 Thymeleaf Processing objects in

Let's take a look thymeleaf How to deal with object information in template , If we're doing a personal blog , Need to be To the front-end blogger related information to show , So we'll encapsulate it as a blogger object , such as :

public class Blogger {
private Long id;
private String name;
private String pass;
//set get ......

And then in controller In the layer :

public String getBlogger(Model model) {
Blogger blogger = new Blogger(1L, " Rational thinking ", "123456");
model.addAttribute("blogger", blogger);
return "blogger";

Let's initialize a Blogger object , Then put the object in Model in , Then return to blogger.html Page to render . Next, let's write another blogger.html To render blogger Information :

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<meta charset="UTF-8">
<title> Blogger information </title>
<form action="" th:object="${blogger}" >
The user id :<input name="id" th:value="${blogger.id}"/><br>
User name :<input type="text" name="username" th:value="${blogger.getName()}" /><br>
password :<input type="text" name="password" th:value="*{pass}" />

It can be seen that , stay thymeleaf In the template , Use th:object="${}" To get object information , Then there are three ways to get object properties in the form . as follows :

 Use th:value="*{ Property name }"
Use th:value="${ object . attribute name }", Object refers to the object used above th:object The object of acquisition
Use th:value="${ object .get Method }", Object refers to the object used above th:object The object of acquisition

It can be seen that , stay Thymeleaf It's like writing java Write code the same way , Very convenient . We type in the browser localhost:8080/thymeleaf/getBlogger Let's test the data :

4.3 Thymeleaf In dealing with List

Handle List Words , It's similar to dealing with the objects described above , But it needs to be in thymeleaf In the middle of Traverse . I First of all, we're in Controller Simulate one in List

public String getList(Model model) {
Blogger blogger1 = new Blogger(1L, " Rational thinking ", "123456");
Blogger blogger2 = new Blogger(2L, " empathy ", "123456");
List<Blogger> list = new ArrayList<>();
model.addAttribute("list", list);
return "list";

Next we write a list.html To get the list Information , And then in list.html Go through this in list. as follows :

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<meta charset="UTF-8">
<title> Blogger information </title>
<form action="" th:each="blogger : ${list}" >
The user id :<input name="id" th:value="${blogger.id}"/><br>
User name :<input type="text" name="password" th:value="${blogger.name}"/><br>
The login password :<input type="text" name="username" th:value="${blogger.getPass()}"/>

It can be seen that , It's almost the same as dealing with single object information ,Thymeleaf Use th:each Traversal ,${} take model Parameters passed from , Then customize list Every object taken out of , This is defined as blogger. The form can be used directly ${ object . Property name } To get list Property values of objects in , It's fine too Use ${ object .get Method } To get , This is the same as dealing with object information above , But it can't be used *{ Property name } To get the properties in the object ,thymeleaf Template cannot be obtained .

4.4 Other commonly used thymeleaf operation

Let's summarize thymeleaf Some common tag operations in

Thymeleaf There are many other uses , There is no summary here , For details, please refer to Thymeleaf Of Official documents (v3.0). The main thing is to learn how to Spring Boot To use thymeleaf, Encountered the corresponding tag or The author's method , Check the official documents .

5. summary

Thymeleaf stay Spring Boot Is very widely used in , This lesson mainly analyzes thymeleaf The advantages of , With And how to Spring Boot Integrated and used in thymeleaf Templates , Including dependence 、 To configure , Acquisition of relevant data take 、 And some precautions and so on . Finally, some thymeleaf Tags commonly used in , In the actual project More use , You can master it by consulting more ,thymeleaf Some of the tags or methods in need not be memorized , be used What to look up , The key is to be able to Spring Boot In the integration , Use more, practice makes perfect .

Hope to continue to pay attention to the follow-up update article ! Have a clear goal for your technical ability !


  1. HttpServletRequest, obtaining request header and request body through request, solving Chinese garbled code and other problems
  2. Mybatis learning notes - one to one, one to many, many to many association query
  3. Mybatis learning notes - basic concepts and operation
  4. Spring Cloud 升级之路 - 2020.0.x - 3. Undertow 的 accesslog 配置
  5. Spring cloud upgrade road - 2020.0. X - 3. Accesslog configuration of undertow
  6. 被Java培训机构坑骗后,我在这里找回了自信
  7. After being cheated by java training institutions, I found my confidence here
  8. Linux下安装Mysql出现的常见问题以及解决办法
  9. Common problems and solutions of installing MySQL under Linux
  10. java并发编程JUC第十二篇:AtomicInteger原子整型
  11. Java Concurrent Programming JUC Chapter 12: atomicinteger atomic integer
  12. 面经手册 · 第29篇《Spring IOC 特性有哪些,不会读不懂源码!》
  13. Chapter 29 "what are the features of spring IOC? I can't understand the source code! 》
  14. 浅析linux容器--Docker
  15. Analysis of Linux container -- docker
  16. 换种方法学操作系统,轻松入门Linux内核
  17. 浅析linux容器--Docker
  18. Another way to learn operating system, easy access to Linux kernel
  19. Analysis of Linux container -- docker
  20. 手摸手教你阅读和调试大型开源项目 ZooKeeper
  21. Hand in hand teaching you to read and debug large open source project zookeeper
  22. 基于SpringBoot 在线答题系统 含小程序!
  23. 10个优秀开源JavaScript模板引擎
  24. JavaScript基础知识及写法
  25. Based on springboot online answering system, including small procedures!
  26. 重磅!谷歌Fuchsia操作系统将支持运行Linux应用程序
  27. (四十) springcloud分布式商城之跟我学习SpringCloud-Gateway整合Eureka路由转发
  28. Spring IOC 特性有哪些,不会读不懂源码!
  29. 手摸手教你阅读和调试大型开源项目 ZooKeeper
  30. 10 excellent open source JavaScript template engines
  31. Basic knowledge and writing method of JavaScript
  32. win10安装mysql5.7
  33. Heavy weight! Google's Fuchsia operating system will support running Linux applications
  34. (40) Spring cloud distributed mall learn from me spring cloud gateway integrates Eureka routing and forwarding
  35. What are the spring IOC features? I can't understand the source code!
  36. Hand in hand teaching you to read and debug large open source project zookeeper
  37. Install mysql5.7 in win10
  38. SCIP:构造数据抽象--数据结构中队列与树的解释
  39. Spring Cloud+Nacos实现服务注册中心(Hoxton版本)
  40. rabbitmq-server的安装与升级
  41. SCIP: constructing data abstraction -- Explanation of queue and tree in data structure
  42. Spring cloud + Nacos to implement service registry (Hoxton version)
  43. Installation and upgrade of rabbitmq server
  44. Lei Jun: Xiaomi's spring conference has been largely streamlined, which will take at least four hours. Some products will be directly released on Weibo
  45. IntelliJ IDEA 2021最新激活码(亲测有效,可激活至 2089 年)
  46. java版本spring cloud+spring boot+mybatis 分布式商城 微服务商城 多租户商城 电子商务 直播带货商城 社交电商
  47. win10安装Redis5.0
  48. (十五)springboot电子商务商城之SpringCloud-使用Eureka集群搭建实现高可用服务注册中心
  49. (十四)springboot电子商务商城之SpringCloud-Eureka自我保护模式和InstanceID的配置
  50. 花生壳内网穿透(Linux版)
  51. Docker部署elasticsearch(单机)
  52. (十三)springboot电子商务商城之SpringCloud-使用Eureka集群搭建实现高可用服务注册中心
  53. (十二)springboot电子商务商城之Eureka注册中心开启密码认证
  54. 七、Spring Boot 集成 Thymeleaf 模板引擎
  55. mysql 命令行秒复制数据库
  56. Windows安装Mysql(msi 图形安装)
  57. The latest activation code of IntelliJ idea 2021
  58. Java应用全链路启动速度提升至15s,阿里云SAE能力再升级
  59. Linux基础命令
  60. Who moved your red envelope? Risk control report of 2021 spring festival activities