SpingBoot学习(5) --引入Thymeleaf

概述:Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成。Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用

 

一:创建一个Thymeleaf模块

 

二:引入了Thymeleaf后,我们只需要将静态资源文件放在/resources/templates下就可以进行访问了。

例如:我在/resources/templates下写一个success.html页面

然后我写一个controller访问该文件即可:

@Controller
public class HelloController {


    @RequestMapping("/success")
    public String success(){
        return "success";
    }
}

发起success请求:

 

三:使用Thymeleaf语法:

基本使用规则可以到Thymeleaf官网查阅:https://www.thymeleaf.org/

1、使用Thymeleaf在页面上取值

(1)、在Controller中添加请求域数据

@RequestMapping("/success")
public String success(Map<String ,Object> map){
    map.put("name","筱筱创");
    return "success";
}

(2)、在页面中进行取值

1、引入thymeleaf名称空间:

<html lang="en"  xmlns:th="http://www.thymeleaf.org">

2、取值

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功来到success页面!</h1>
<h2 th:text="${name}">这里是展示名字的</h2>

</body>
</html>

运行查看结果:

常用标签:

th:text:转义特殊字符

th:utext:不转义特殊字符

th:each:遍历

th:if:条件判断

th:attr:任意属性修改

th:switch:提供选择器

th:case:为switch提供case选项

等等。

 

 

表达式:

获取变量值:${...}

<h2 th:text="${name}">这里是展示名字的</h2>

选择变量表达式*{...}:

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text={nationality}">Saturn</span>.</p>
</div> 
等价于
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

 这也是Thymeleaf非常好的一个特性:在无网络的情况下也能运行,也就是完全可以前端先写出页面,模拟数据展现效果,后端人员再拿此模板修改即可!

 

3.链接表达式: @{…} 

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<a href="details.html" th:href="@{order/{orderId}/details(orderId=${o.id})}">Content路径,默认访问static下的order文件夹</a>

 

posted @ 2022-04-05 16:56  筱筱创  阅读(483)  评论(1编辑  收藏  举报