1.什么是 FreeMarker?
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比, Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。
可以看一下官网对其的介绍:Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎。Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板-HTML可以在浏览器中正确显示,并且可以作为静态原型工作,从而可以在开发团队中加强协作。Thymeleaf拥有用于Spring Framework的模块,与您喜欢的工具的大量集成以及插入您自己的功能的能力,对于现代HTML5 JVM Web开发而言,Thymeleaf是理想的选择-尽管它可以做很多事情。
2.如何在springboot中进行使用呢?
2.1引入pom.xml依赖
<!-- thymeleaf 模板启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2配置文件application.properties中添加配置
############################################################
#
# thymeleaf 模板
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# 关闭缓存
spring.thymeleaf.cache=false
2.3创建Controller测试类
package com.bw.auto.modules.web;
import com.bw.auto.resource.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafTest {
@Autowired
private Resource resource;
@RequestMapping("/thymeleafTest")
public String index(Model model){
model.addAttribute("name",resource.getName());
model.addAttribute("number",resource.getNumber());
return "thymeleaf";
}
}
2.4前端显示页面创建(html的创建)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}"></h1>
<h1 th:text="${number}"></h1>
</body>
</html>
至此整个项目就算完成了,我们看一下项目的工程结构,并且启动一下看看效果!
启动后输入地址:http://localhost:8080/thymeleafTest
这里多说两句,关于Thymeleaf的表达式如何使用,可以去官网查看规则,有兴趣的可以去看看!https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls