Thymeleaf简单入门(一)

本文主要是对于spring boot中thymeleaf非常浅显的知识进行介绍,并不深入了解,只接触表面,对一些较复杂的内容也不过多描述。如文中有错误之处,望不吝赐教,谢谢~

一、Thymeleaf简介

Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本等文件。
模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,如在web开发中的常用的html文档。
在spring boot的开发中为什么不使用jsp而使用thymeleaf呢?最大的原因是因为较高版本的spring boot不兼容jsp(通过一些特殊配置可以兼容),所以使用thymeleaf(当然还有其他选择)。

二、Thymeleaf简单入门

(1)新建spring boot项目
(2)引入thymeleaf依赖

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

(3)新建HelloController类

package com.example.springboot_study_demo3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {


    //向success.html页面加载信息
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("success","成功");
        return "success";
    }
}

(4)在resources/templates目录下新建success.html文件

<!DOCTYPE html>

<!--thymrleaf名称空间 xmlns:th="http:www.thymeleaf.org-->
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:text="${success}"></div>
</body>
</html>

(5)启动项目,然后再在浏览器中输入http://localhost:8080/success,便可看到如下界面,说明成功使用thymeleaf,此时在前端页面已成功加载信息(“成功”)。

在这里插入图片描述

上面这个例子很简单,和之前的spring boot的例子差不多,唯一不同的便是引入thymeleaf依赖以及将html文件放入resources/templates目录。需要注意的便是thymeleaf的一些语法。

三、Thymeleaf基础语法

  • th:任意属性

改变当前属性元素里面的文本内容,如 th:text=“success”

  • 获取变量表达式: ${…}

获取变量值

  • 选择表达式:*{…}

{…}与 . . . d i v , 使 {...}功能相同,唯一不同的是其增添了一个功能:例如在div里,先使用了 {…}获取变量,则后续可用{…}代替这个变量

<!--官方文档示例-->
<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>
  • @{…}

定义url

<!--官方文档示例-->
<!-- 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>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
  • #{…}

获取国际化内容

  • 片段引用表达式:~{…}

一般是引用html片段

在这里插入图片描述
2020.03.29

发布了82 篇原创文章 · 获赞 91 · 访问量 9499

猜你喜欢

转载自blog.csdn.net/ataraxy_/article/details/105178234