一、认识 Thymeleaf
二、第一个实例
项目结构
1.创建springboot项目添加web起步依赖和thymeleaf依赖。
pom.xml文件
- "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.0modelVersion>
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parentartifactId>
- <version>2.7.3version>
- <relativePath/>
- parent>
- <groupId>com.itgroupId>
- <artifactId>027-thymeleaf-firstartifactId>
- <version>1.0.0version>
-
-
- <properties>
- <java.version>1.8java.version>
- properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-thymeleafartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- plugin>
- plugins>
- build>
-
- project>
2.创建controller包下的HelloThymeleafController类
- package com.it.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
-
- import javax.servlet.http.HttpServletRequest;
-
- @Controller
- public class HelloThymeleafController {
-
- @GetMapping("/hello")
- public String helloThymeleaf(Model model,HttpServletRequest httpServletRequest){
- //添加数据到request作用域,模板引擎可以从request中获取数据
- httpServletRequest.setAttribute("data","欢迎使用thymeleaf模板引擎");
-
- model.addAttribute("mydata","model中的数据");
- //指定视图(模板引用使用的页面html)
- return "hello";
- }
- }
3.hello.html文件
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>hello.htmltitle>
- head>
- <body>
- <h3>使用模板thymeleaf的例子h3>
- <p th:text="${data}">想显示数据p>
- <p th:text="${mydata}">显示数据p>
-
- body>
- html>
4.进入主函数入口类启动项目进行测试
测试结果中使用了thymeleaf模板的标签,这些标签中的数据会被request传递过来的数据代替,以实现数据更新。