Spring Boot使用模板引擎 Thymeleaf的方法
Thymeleaf:一款用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,FreeMarker等,它也可以轻易的与spring mvc等web框架进行集成作为web应用的模板引擎。
官网地址:Thymeleaf
一、引入依赖包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
二、配置文件
新建application.yml文件(resources中)
spring: thymeleaf: #prefix:指定模板所在目录 prefix: classpath:/templates/ #check-tempate-location:检查模板路径是否存在 check-tempate-location: true #cache:是否缓存,开发模式设置为false,避免修改模板需重启服务器,线上为true,可以提高性能 cache: true suffix: .html encoding: UTF-8 mode: HTML5
三、编写模板文件:
在templates文件夹中创建html文件
例如index.html
<!DOCTYPE html>
<!-- 注意:添加th,idea 有智能提示-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<H1 th:text="${tt}"></H1>
</body>
</html>四、编写Controller
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyThymeleafController {
@RequestMapping("/myThymeleaf")
public String myThymeleaf(HttpServletRequest request) {
request.setAttribute("tt", "123");
return "myThymeleaf";
}
}其他模板:
Spring Boot提供了默认配置的模板引擎主要还有其他几种:
FreeMarker
Velocity
Groovy
Mustache
大家可以自己选择