thymleft介绍
Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。
整合thymleft
使用springboot 来集成使用Thymeleaf可以大大减少单纯使用thymleaf的代码量,所以我们接下来使用springboot集成使用thymeleaf.
实现的步骤为:
创建一个sprinboot项目
添加thymeleaf的起步依赖
添加spring web的起步依赖
编写html 使用thymleaf的语法获取变量对应后台传递的值
编写controller 设置变量的值到model中
(1)创建工程(步骤略,项目名称自定义)
<!--集成SpringBoot-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<!--web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
(2)创建html
在resources中创建templates目录,在templates目录创建 templates_1.html,代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf的入门</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!--输出hello数据-->
<p th:text="${hello}"></p>
</body>
</html>
代码详解:
<html xmlns:th="http://www.thymeleaf.org">:这句声明使用thymeleaf标签
<p th:text="${hello}"></p>:这句使用 th:text="${变量名}" 表示 使用thymeleaf获取文本数据,类似于EL表达式。
(3)修改application.yml配置
创建application.yml,并设置thymeleaf的缓存设置,设置为false。默认加缓存的,用于测试。
spring:
thymeleaf:
cache: false
(4)控制层
创建controller用于测试后台 设置数据到model中。
创建com.lailai.controller.TestController,代码如下:
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到templates_1页面
* @param model
* @return
*/
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("hello","hello welcome");
return "templates_1";
}
}
(5)测试
创建启动类com.itheima.ThymeleafApplication
,代码如下:
@SpringBootApplication
public class ThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(ThymeleafApplication.class,args);
}
}
访问
thymleft实现页面跳转
.java代码 如下方式,templates目录下的HTML页面默认不能被直接访问,需要通过controller来访问,由thymeleaf来渲染
@RequestMapping("index")
public class SpringBootController {
@RequestMapping("/thymeleaf")
public String thymeleaf(Model model) {
j
model.addAttribute("name", "qushen");
System.out.println("从Controller跳转thymeleaf");
return "user/thymeleaf";
}
}
HTML写法如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>hello Spring boot!</div>
<p th:text="${name}">Welcome to our grocery store!</p>
</body>
</html>