一、Thymeleaf是什么?
- 简单来说Thymeleaf和JSP、Freemaker等语言一样,是一个模板驱动语言。并且因为Thymeleaf的功能比JSP更加强大,SpringBoot默认整合的前端驱动语言就是Thymeleaf所以现在多数项目都是使用Thymeleaf作为前端驱动语言。
二、整合步骤
1. IDE创建项目
1.项目截图
搭建springboot-thymeleaf名称的项目
引入spring web 和thymeleaf相关jar包
2.pom文件内容
<?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.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-thymeleaf</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.controller层内容
@Controller
@RequestMapping("thymeleafController")
public class ThymeleafController {
/****
* description: goThymeleaf
* version: 1.0 ->
* date: 2022/1/28 16:25
* author: xiaYZ
* iteration: 迭代说明
* @param
* @return org.springframework.web.servlet.ModelAndView
*/
@RequestMapping("goThymeleaf")
@Description("跳转到thymeleaf页面")
public ModelAndView goThymeleaf(){
ModelAndView view = new ModelAndView();
view.addObject("message","访问thymeleaf成功");
view.setViewName("thymeleafTest");
return view;
}
}
4.thymeleaf前端内容
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${message}"></div>
</body>
</html>
5.文件位置
注意:前端驱动语言文件放在template文件夹中
6.运行截图
访问对应的接口,跳转的thymeleaf对应的页面并返回提示信息。
注意:因为springBoot默认整合thymeleaf所以不需要在application配置文件中配置信息,但是如果前端驱动语言是JSP或者是FreeMaker则取需要配置