springboot 与thymeleaf 集成
Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。
–摘自官网https://www.thymeleaf.org/
一、简介
Thymeleaf是一种服务器端Java模板引擎,用于将数据渲染为HTML、XML、JavaScript等格式,并在Web浏览器中呈现给用户。 具体来说,Thymeleaf充当着视图层的角色,与控制器和模型一起构成了典型的MVC(模型-视图-控制器)设计模式中的视图部分。 Thymeleaf模板引擎允许我们在模板中使用HTML标记、JavaScript表达式和Thymeleaf表达式等,以动态地生成Web页面。Thymeleaf提供了一些特殊的属性和标签,以支持与控制器和模型之间的数据绑定和交互。
相比于传统的前端技术(如HTML、CSS和JavaScript),Thymeleaf更注重后端的处理逻辑和数据交互。Thymeleaf能够从服务器端动态地生成页面,这意味着我们可以将服务器端的数据直接渲染到页面上,从而减少了大量的前端开发工作。同时,由于Thymeleaf能够与后端Java代码无缝集成,因此我们可以很方便地使用Java提供的各种类库和框架,进一步简化了开发工作。
二、thymeleaf 有哪些优势
因为jsp页面存在劣势,它的本质是Servlet,还是一个类,只要是类就离不开JVM。我们无法通过浏览器直接查看JSP页面的效果,这不便于前端页面的实现。
替代JSP:
1、模板引擎,具备JSP的功能,但是比JSP更加强大,可以直接通过浏览器查看页面效果。
2、前后端分离,Vue。
- 动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
- 开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速地实现表单绑定、属性编辑器、国际化等功能。
- 与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。
三、如何使用thymeleaf
我们使用 idea 的默认 springboot initializr 自动构建,使用的镜像构建地址为:https://start.aliyun.com/
3.1 引入依赖
<!--使用thymelaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
## 这是一个完整的 pom.xml依赖
<?xml version="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.0</modelVersion>
<groupId>com.fashion</groupId>
<artifactId>springboot-day5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-day5</name>
<description>springboot-day5</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.5.0</spring-boot.version>
<!-- <spring-boot.version>2.4.2</spring-boot.version>-->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--使用thymelaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.fashion.SpringbootDay5Application</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3.2 编写yml 配置文件
# 日志设置
logging:
level:
com.fashion: debug
# thymeleaf 模版配置,默认就是这样
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
3.3 编写controller
@Controller
//@RequestMapping("/home/")
public class IndexController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("index")
public String index(Model model) {
model.addAttribute("name","小张");
model.addAttribute("age",19);
model.addAttribute("birthday",new Date());
User user = new User("小明",23,new Date());
model.addAttribute("user",user);
List<User> userList = Arrays.asList(new User("小明",23,new Date())
,new User("小张",33,new Date())
,new User("小王",43,new Date()));
model.addAttribute("userList",userList);
model.addAttribute("textHtml","<span style='color:red;'>这是一个带有html标签样式的数据</span>");
return "index";
}
}
3.4 编写thymeleaf 数据展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="margin-left: 10%;">
<h1>springboot 与 thymeleaf 模版集成</h1>
<div>
<h3> 单个字符获取================》 </h3>
<div>姓名:<span th:text="${name}"/>, 年龄:<span th:text="${age}"/>,生日:<span th:text="${#dates.format(birthday,'yyyy-MM-dd')}"/> </div>
</div>
<div>
<h3> 解析含有html 标签的数据 ================》 </h3>
<div>
<span th:utext="${textHtml}"></span>
</div>
</div>
<div>
<h3> 这是一个赋值给表单的input框的值 ================》 </h3>
<div>
<span> 这是一个input 标签</span>
<input th:value="${name }" th:name="name">
</div>
</div>
<div>
<h3> 对象获取方式================》</h3>
<div>姓名:<span th:text="${user.name}"/>, 年龄:<span th:text="${user.age}"/>,生日:<span th:text="${#dates.format(user.birthday,'yyyy-MM-dd')}"/> </div>
</div>
<div>
<h3> list 多条数据 获取================》</h3>
<ul th:each="user,status:${userList}">
<li>序号:<span th:text="${status.count}"/> </li>
<li>姓名:<span th:text="${user.name}"/> </li>
<li>年龄:<span th:text="${user.age}"/> </li>
<li>生日:<span th:text="${#dates.format(user.birthday,'yyyy-MM-dd')}"/> </li>
</ul>
</div>
<div>
<h3> list 多条数据 条件渲染================》</h3>
<ul th:each="user,status:${userList}">
<li>序号:<span th:text="${status.count}"/> </li>
<li>姓名:<span th:text="${user.name}"/> </li>
<li>所属阶段:
<span th:if="${user.age gt 30}">中年</span>
<span th:if="${user.age <= 30}">小青年</span>
</li>
</ul>
</div>
</div>
</body>
</html>
3.5 测试结果
我们使用基本数据类型,对象类型,集合类型,多个测试
3.6 thymeleaf 语法介绍
包含
- th属性
- 标准表达式语法
- 代码块表达式
- 消息表达式
- 连接表达式
- 连接表达式
- 变量表达式
- 常用内置对象
1、th属性
html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。
一、th:text:设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。用于标签属性
二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src ,th:href。用于input 框
三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置;用于标签
四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。
五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景
六、th:fragment:定义代码块,方便被th:insert引用
七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。
八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。
th 使用注意事项
一、若要使用Thymeleaf语法,首先要声明名称空间:
xmlns:th="http://www.thymeleaf.org"
二、th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。
三、变量表达式中提供了很多的内置方法,内置方法是用
#
开头,不要与#{}
消息表达式弄混。四、th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大
th 实际使用
- 条件比较 ,Thymeleaf支持常见的条件比较,如==、!=、<、>等
<div th:if="${user.age} > 18">成年用户</div>
- switch 分支使用,用于多分支条件判断
<div th:switch="${user.role}"> <p th:case="'admin'">管理员</p> <p th:case="'user'">普通用户</p> <p th:case="*">未知角色</p> </div>
- 循环
<ul> <li th:each="item : ${items}" th:text="${item.name}">默认列表项</li> </ul>
- 逻辑运算符
我们可以使用加(+)、减(-)、乘(*)、除(/)和取余(%)等基本算术运算符来进行数值计算 <p th:text="${user.age} + 1">年龄加一</p>
- 内联,用于在文本和属性中直接插入表达式。这种表达式允许我们在文本内容和HTML属性中直接插入动态数据,从而实现页面内容的灵活定制。
<p>你好,[[${user.name}]]!</p>
- 字符串拼接
<p th:text="'Hello, ' + ${user.name} + '!'">默认问候</p>
2、标准表达式语法
${...}
变量表达式,Variable Expressions
@{...}
链接表达式,Link URL Expressions
#{...}
消息表达式,Message Expressions
~{...}
代码块表达式,Fragment Expressions
*{...}
选择变量表达式,Selection Variable Expressions
3、~{…} 代码块表达式
推荐:
~{templatename::fragmentname}
支持:
~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路径:
/resources/templates/templatename.html
,要注意文件的路径。fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:
th:fragment="fragmentname"
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。\
th:insert:
将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:
将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:
将代码块片段包含的内容插入到使用了th:include的HTML标签中,
用一个官方例子来区分三者的不同
<!--th:fragment定义代码块标识-->
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
<!--三种不同的引入方式-->
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
4、#{…} 消息表达式
消息表达式一般用于国际化的场景。结构:th:text=“#{msg}” 。
5、@{…} 链接表达式
链接表达式的好处
不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问链接表达式结构
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
实际使用
<a th:href="@{/result}">...</a> <!--整个页面 href和src属性的标签自动拼接项目地址 http://ip:端口/项目名/ --> <base th:href="@{/}" th:src="@{/}">
6、${…}变量表达式
变量表达式有丰富的内置方法,使其更强大,更方便
- 变量表达式功能
- 可以获取对象的属性和方法
- 可以使用ctx,vars,locale,request,response,session,servletContext内置对象
- 可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法
7、常用的内置对象
一、ctx :上下文对象。
二、vars :上下文变量。
三、locale:上下文的语言环境。
四、request:(仅在web上下文)的 HttpServletRequest 对象。
五、response:(仅在web上下文)的 HttpServletResponse 对象。
六、session:(仅在web上下文)的 HttpSession 对象。
七、servletContext:(仅在web上下文)的 ServletContext 对象
实际使用
// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"
8、常用的内置方法
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
二、numbers:数值格式化方法,常用的方法有:formatDecimal等
三、bools:布尔方法,常用的方法有:isTrue,isFalse等
四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等
实际使用
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>ITDragon Thymeleaf 内置方法</title>
</head>
<body>
<h2>ITDragon Thymeleaf 内置方法</h2>
<h3>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
<p>Old Str : <span th:text="${itdragonStr}"/></p>
<p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
<p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
<p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
<p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
<p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
<p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
<p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
<p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
<p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>
<h3>#numbers </h3>
<div>
<p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p>
<p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p>
</div>
<h3>#bools </h3>
<div th:if="${#bools.isTrue(itdragonBool)}">
<p th:text="${itdragonBool}"></p>
</div>
<h3>#arrays </h3>
<div th:if="${not #arrays.isEmpty(itdragonArray)}">
<p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p>
<p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p>
<p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p>
</div>
<h3>#lists </h3>
<div th:if="${not #lists.isEmpty(itdragonList)}">
<p>size : <span th:text="${#lists.size(itdragonList)}"/></p>
<p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p>
<p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p>
</div>
<h3>#maps </h3>
<div th:if="${not #maps.isEmpty(itdragonMap)}">
<p>size : <span th:text="${#maps.size(itdragonMap)}"/></p>
<p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p>
<p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p>
</div>
<h3>#dates </h3>
<div>
<p>format : <span th:text="${#dates.format(itdragonDate)}"/></p>
<p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
<p>day : <span th:text="${#dates.day(itdragonDate)}"/></p>
<p>month : <span th:text="${#dates.month(itdragonDate)}"/></p>
<p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p>
<p>year : <span th:text="${#dates.year(itdragonDate)}"/></p>
<p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p>
<p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p>
<p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p>
<p>second : <span th:text="${#dates.second(itdragonDate)}"/></p>
<p>createNow : <span th:text="${#dates.createNow()}"/></p>
</div>
</body>
</html>
3.7 静态资源使用
使用thymeleaf模板项目中静态资源默认放在resources路径下static目录中
1、引入静态资源 css
<link rel="stylesheet" th:href="@{/demo.css }">
2、引入js资源
<script type="text/javascript" th:src="@{/demo.js }"></script>
3、使用
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>测试静态资源</title> <link rel="stylesheet" th:href="@{/demo.css }"> <script type="text/javascript" th:src="@{/demo.js }"></script> </head> <body> <h1 class="back_color">spring boot 静态资源引入</h1> <h4 class="back_color">姓名:<span th:text="${name}" /></h4> </body> <script type="text/javascript"> test(); // 通过内联表达式获取根项目 let applicationContext = "[[@{/ }]]"; console.log("项目根目录",applicationContext); </script> </html>