SpringBoot入门学习笔记-13-thymeleaf模板引擎&本项目源码

thymeleaf我们主要用来将html文本渲染生成一个html网页,返回给客户端。

模板引擎是一种可以把程序员提供的数据和模板通过模板引擎转换成固定格式来动态生成HTML的技术

thymeleaf是其中一个主流的模板引擎,也是springboot推荐的。

一、安装thymeleaf,添加spring-boot-starter-thymeleaf。

直接在mavn仓添加依赖即可,maven的话添加pom文件:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

gradle的话,添加build.gradle:

 implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

二、在templates中添加静态资源html文件

随便写一个hello.html 示例文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
<p>hello,Thymeleaf!</p>

</body>
</html>

但是位置不能放错,项目src/main/resources/templates/hello.html

 三、controller中返回html文件

  @RequestMapping("/hello")
    public String hello(Model model){
        return "hello.html";
    }

 然后,我们通过网页访问就会看到写的html内的内容了。(POST也是可以的,看你RequestMapping中有没有限定请求类型)

注意:返回文件不能用@RestController,要用@Controller。

四、yml中配置常用属性

可以把像网页后缀,网页位置都在yml配置中设置好,比如默认的文件夹位置是templates也可以更改。常见配置参考spring.thymeleaf:

spring:
  application:
    name: laoluo-base
  thymeleaf:
    # 关闭thymeleaf的缓存,开发过程中无需重启
    cache: false
    # 设置默认编码
    encoding: utf-8
    mode: HTML5
    # 设置页面后缀
    suffix: .html
    # 设置页面的存储路径
    prefix: classpath:/templates/

 这样配置以后就会全局生效,比如原来

return "hello.html",就可以改为return "hello";

五、设置属性。

在Controller中,我们看到有一个Model类型的model参数,这个就是用来传参的。

1、我们先看传参示例:

    @RequestMapping("/hello")
    public String hello(Model model){
        // 传单个参数
        model.addAttribute("hello","hello Thymeleaf!");
        
        // 通过map传参
        HashMap hashMap =new HashMap<>();
        hashMap.put("k1","k1value");
        hashMap.put("k2","k2value");
        hashMap.put("k3","k3value");
        model.addAllAttributes(hashMap);
        
        return "hello";
    }

完整截图:

 2、看接收参数示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
<p>hello,Thymeleaf!</p>
<h1 th:text="${hello}"></h1>
<h1 th:text="${k1}"></h1>
<h1 th:text="${k2}"></h1>
<h1 th:text="${k3}"></h1>
</body>
</html>

截图:

 3、我们也可以传map对象。

通过model传一个对象

model.addAttribute("map",hashMap);通过"${map.key}"获取值。
        HashMap hashMap =new HashMap<>();
        hashMap.put("k1","k1value");
        hashMap.put("k2","k2value");
        hashMap.put("k3","k3value");
        model.addAttribute("map",hashMap);

 六、Thymeleaf 语法。

Thymeleaf的主要作用是把model中的数据渲染到html中,因此其语法主要是如何解析model中的数据,因此其语法主要是如何解析model中的数据。

1、内置方法和对象。

一些环境相关对象
对象    作用
#ctx    获取Thymeleaf自己的Context对象
#requset    如果是web程序,可以获取HttpServletRequest对象
#response    如果是web程序,可以获取HttpServletReponse对象
#session    如果是web程序,可以获取HttpSession对象
#servletContext    如果是web程序,可以获取HttpServletContext对象
Thymeleaf提供的全局对象:
对象    作用
#dates    处理java.util.date的工具对象
#calendars    处理java.util.calendar的工具对象
#numbers    用来对数字格式化的方法
#strings    用来处理字符串的方法
#bools    用来判断布尔值的方法
#arrays    用来护理数组的方法
#lists    用来处理List集合的方法
#sets    用来处理set集合的方法
#maps    用来处理map集合的方法

2、使用示例,hello.html中通过${name}使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
<p>hello,Thymeleaf!</p>
<!--在JSP中通过EL表达式进行获取-->
<!--${hello}-->
<!--HTML中用法-->

    这样直接引用变量无效。
    <p>${hello}</p>

    可以放在一些无意义的标签,通过th:text方法引用
    <p><span th:text="${hello}"></span></p>

    内置对象使用示例,toLowerCase:
    <div th:text="${#strings.toLowerCase(hello)}">

</body>
</html>

3、Thymeleaf 还提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用,其中常用 th 属性及其示例如下表。

更多的属性下表,以下更摘录自Thymeleaf教程(10分钟入门) (biancheng.net)

属性描述示例
th:id替换 HTML 的 id 属性
 
    
  • <input id="html-id" th:id="thymeleaf-id" />
th:text文本替换,转义特殊字符
 
    
  • <h1 th:text="hello,bianchengbang" >hello</h1>
th:utext文本替换,不转义特殊字符
 
    
  • <div th:utext="'<h1>欢迎来到编程帮!</h1>'" >欢迎你</div>
th:object在父标签选择对象,子标签使用 *{…} 选择表达式选取值。
没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。
同时即使选择了对象,子标签仍然可以使用变量表达式。
 
    
  • <div th:object="${session.user}" >
  • <p th:text="*{fisrtName}">firstname</p>
  • </div>
th:value替换 value 属性
 
    
  • <input th:value = "${user.name}" />
th:with局部变量赋值运算
 
    
  • <div th:with="isEvens = ${prodStat.count}%2 == 0" th:text="${isEvens}"></div>
th:style设置样式
 
    
  • <div th:style="'color:#F00; font-weight:bold'">编程帮 www.biancheng.net</div>
th:onclick点击事件
 
    
  • <td th:onclick = "'getInfo()'"></td>
th:each遍历,支持 Iterable、Map、数组等。
 
 
    
  • <table>
  • <tr th:each="m:${session.map}">
  • <td th:text="${m.getKey()}"></td>
  • <td th:text="${m.getValue()}"></td>
  • </tr>
  • </table>
th:if根据条件判断是否需要展示此标签
 
    
  • <a th:if ="${userId == collect.userId}">
th:unless和 th:if 判断相反,满足条件时不显示
 
    
  • <div th:unless="${m.getKey()=='name'}" ></div>
th:switch与 Java 的 switch case语句类似
通常与 th:case 配合使用,根据不同的条件展示不同的内容
 
    
  • <div th:switch="${name}">
  • <span th:case="a">编程帮</span>
  • <span th:case="b">www.biancheng.net</span>
  • </div>
th:fragment模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段
 
    
  • <footer th:fragment="footer">插入的内容</footer>
th:insert布局标签;
将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。
 
    
  • <div th:insert="commons/bar::footer"></div>
th:replace布局标签;
使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。
 
    
  • <div th:replace="commons/bar::footer"></div>
th:selectedselect 选择框选中
 
    
  • <select>
  • <option>---</option>
  • <option th:selected="${name=='a'}">
  • 编程帮
  • </option>
  • <option th:selected="${name=='b'}">
  • www.biancheng.net
  • </option>
  • </select>
th:src替换 HTML 中的 src 属性 
 
    
  • <img th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" />
th:inline内联属性;
该属性有 text、none、javascript 三种取值,
在 <script> 标签中使用时,js 代码中可以获取到后台传递页面的对象。
 
    
  • <script type="text/javascript" th:inline="javascript">
  • var name = /*[[${name}]]*/ 'bianchengbang';
  • alert(name)
  • </script>
th:action替换表单提交地址
 
    
  • <form th:action="@{/user/login}" th:method="post"></form>

这个网页上讲得很详细。更多内容请见下面的网页:

Thymeleaf教程(10分钟入门) (biancheng.net)http://c.biancheng.net/spring_boot/thymeleaf.html

七、本项目源码下载。

截止到目前为止,因为不涉及数据库、redis、nacos等,都是单体应用,不论怎么调整都可以单独运行的,所以先打个包,上传到gitee,方便网友下载。地址是:laoluo-base: Springboot入门项目。study级 (gitee.com)

后面,开始会涉及一些相关联的组件或服务,所以后面的项目,我会再开一个gitee地址上传。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,你可以使用Thymeleaf作为模板引擎来处理视图层的渲染。Thymeleaf是一种基于HTML的模板引擎,它允许你在HTML模板中嵌入动态数据和逻辑处理。 要在Spring Boot中使用Thymeleaf,你需要遵循以下步骤: 1. 添加Thymeleaf依赖:在你的项目构建文件(例如Maven的pom.xml或Gradle的build.gradle)中,添加Thymeleaf的依赖项。 对于Maven项目,添加以下依赖: ```xml dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;/dependency&gt; ``` 对于Gradle项目,添加以下依赖: ```groovy implementation &#39;org.springframework.boot:spring-boot-starter-thymeleaf&#39; ``` 2. 创建Thymeleaf模板文件:在src/main/resources/templates目录下创建你的HTML模板文件。使用Thymeleaf的语法来嵌入动态数据和逻辑。 示例模板文件(index.html): ```html &lt;!DOCTYPE html&gt; &lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt; &lt;head&gt; &lt;title&gt;Spring Boot Thymeleaf Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Welcome, &lt;span th:text=&quot;${name}&quot;&gt;&lt;/span&gt;!&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; ``` 在这个示例中,我们使用Thymeleaf的语法`th:text=&quot;${name}&quot;`将`name`变量的值插入到HTML文档中。 3. 创建控制器:创建一个Spring MVC控制器来处理请求并返回Thymeleaf视图。 示例控制器: ```java @Controller public class HomeController { @GetMapping(&quot;/&quot;) public String home(Model model) { model.addAttribute(&quot;name&quot;, &quot;John&quot;); return &quot;index&quot;; } } ``` 在这个示例中,我们使用`Model`对象将`name`属性添加到模型中,并将其传递给`index`视图。 这样,当你访问根路径(&quot;/&quot;)时,将会渲染`index.html`模板并显示&quot;Welcome, John!&quot;。 这只是一个简单的示例,Thymeleaf还提供了很多强大的功能,比如迭代、条件渲染、表单处理等。你可以参考Thymeleaf官方文档以了解更多详细信息。 希望这能帮助你了解如何在Spring Boot中使用Thymeleaf作为模板引擎!如果你有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值