模板引擎介绍
常见的模板引擎下:JSP、Velocity、Freemarker、Thymeleaf(SpringBoot推荐)
执行过程:模板(Template)+数据(Data)====交给模板引擎(TemplateEngine)====out写出去
SpringBoot推荐的Thymeleaf模板引擎特点:语法简单,功能更强大
SpringBoot Thymeleaf引擎模板使用
1、引入Thymeleaf模板引擎maven依赖spring-boot-starter-thymeleaf
2、只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染
3、Thymeleaf语法
- 页面导入xmln:th="http://www.thymeleaf.org"eleaf.org"
- th:text="${}"
- th:href="@{/url}" 其中@表示http://localhost:port/项目名
- th:src="@{/url}"
4、开发期间模板引擎页面修改以后,要实时生效
- 禁用模板引擎的缓存,在application.properties配置spring.thymeleaf.cache=false
- 页面修改完成以后,ctrl+f9:重新编译(IDEA环境)
SpringBoot Thymeleaf引擎模板实战
1、引入maven依赖(可以到SpringBoot官网找start启动器)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、编写Controller控制类(自动生成的SpringBoot)
package com.xue.springbootweb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
/**
* @Description
* @Author xuexue
* @Date 2019/9/28 17:25
*/
@Controller
public class TestController {
@RequestMapping(value = "/login")
public String toHelloWorld() {
return "login";
}
}
3、在templates下创建编写login文件(templates由模板引擎自动渲染)
头部引入,编写html时,就会有提示thymeleaf语法信息
xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" th:value="我是内容" />
<span th:text="我是范围"></span>
</body>
</html>
运行结果