Thymeleaf入门第一弹
之前也使用过一段时间的Thymeleaf,不得不说,用起来真的很方便,但是后来由于考研,也就没在接触,最近由于个人需要,
需再次使用Thymeleaf+Spring boot,由于太长时间没有接触,对于Thymeleaf中的一些知识已经不是那么清晰,所以现 再次学
习下Thymeleaf,并根据此作为记录,方便后面查阅。
介绍
Thymeleaf是一个现代的Java模板引擎,在服务器端为两个Web和标准环境操作。它可以处理HTML、XML、Javascript、CSS,甚至纯文本。
从Maven导包
<properties>
<springboot-thymeleaf.version>3.0.2.RELEASE</springboot-thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
文件位置
将静态的html页面放在 resources 下如下图所示,static下放的是静态文件如js,css,img
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
如果你看到这行文字,恭喜你!Thymeleaf 跳转 index 页面成功
</body>
</html>
然后设置Controller进行跳转,返回的值为我们需要跳转的页面的名称,参考代码如下,直接通过输入地址访问的方式是GET因此采用的方式是GetMapping。
package com.caigentan.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ResponseBodyController {
@GetMapping("/")
public String index(){
return "index";
}
}
在浏览器输入:localhost:8080(当你的端口号设置为8080时)若可成功跳转到index.html的渲染页面则表示成功,如下图所示:
Thymeleaf 引擎
Thymeleaf Engine可以解析 Thymeleaf模板,并使用 Java 数据替换Thymeleaf模板上标记的位置 来创建新文本。
当我们在页面中使用Thymeleaf引擎时,我们用th:xx来表示(会替换前面的href),如
第一个href用于当我们在浏览器中直接打开html文件时的跳转,第二个th:href则用于当我们使用Thymeleaf模板引擎时是href他会替换第一个href被浏览器解析
<a href="./caigentan.png" th:href="@{fromjava.asrc}">点击跳转</a>