二、Springboot+Thymeleaf 整合之前后端(文本)交互
一、配置环境
1.1 在上一节的pom.xml
文件中引入thymeleaf 模板依赖:
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
1.2 在配置文件 application.yml
中 编写thymeleaf 的配置
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
mode: HTML5
servlet:
content-type: text/html
encoding: utf-8
二、前端显示后端传输的数据
1.变量传输方式
1.1 前端代码
编写index.html
文件
注意 文件头部要加上
xmlns:th="http://www.thymeleaf.org"
th:text=" ${xxxx}"
-------- thymeleaf 语法 获取文本信息
$
----------- 取值符
${ xxxx}
--------注入的形参 要与后端的一致,不然取不到值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello word</title>
</head>
<body>
<p>大家好</p>
<!--其中,注释是通过alt+enter进行自动生成的,便于IDEA补全,如果不加,IDEA将会报错cannot reslove,-->
<!--/*@thymesVar id="name" type="Java.lang.String"*/-->
<p th:text=" ${name}"></p>
<!--/*@thymesVar id="year" type="java.lang.String"*/-->
<p th:text=" ${year}"></p>
<!--/*@thymesVar id="hobby" type="java.lang.String"*/-->
<p th:text