Springboot 整合 Thymeleaf

Springboot 整合 Thymeleaf

pom 引入 thymeleaf 依赖

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

yml 文件添加 thymeleaf 配置

spring:
  # thymeleaf 模块配置
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: LEGACYHTML5
    encoding: utf-8
    # 关闭页面缓存
    cache: false
    servlet:
      content-type: text/html

添加测试 Controller

package com.example.demo.module.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ThymeleafController {

    @GetMapping(value = "index")
    public ModelAndView hello(@RequestParam(value = "spanText",required = false)String spanText){
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("spanText",spanText);
        return modelAndView;
    }

}

index.html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<span th:text="${spanText}"></span>

</body>
</html>

这里要注意,想要使用 thymeleaf,需要在页面添加 thymeleaf 支持

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

启动项目测试
在这里插入图片描述
可以看到,页面已经能正常展示

Springboot 整合 Thymeleaf 完成!

thymeleaf 语法

1、th属性:
html有的属性,Thymeleaf基本都有,在属性前加 th: 即可。
而常用的属性大概有七八个,其中th属性执行的优先级从1~8,数字越低优先级越高。

th:text :
设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7

th:value:
设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6

th:each:
遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2

th:if:
条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3

th:insert:
代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

th:fragment:
定义代码块,方便被th:insert引用。优先级最低:order=8

th:object:
声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4

th:attr:
修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

2、标准表达式语法:

${...} 变量表达式,Variable Expressions

@{...} 链接表达式,Link URL Expressions

#{...} 消息表达式,Message Expressions

~{...} 代码块表达式,Fragment Expressions

*{...} 选择变量表达式,Selection Variable Expressions

${…} 变量表达式

变量表达式功能

一、可以获取对象的属性和方法

二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象

三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍)

常用的内置对象

一、ctx :上下文对象。

二、vars :上下文变量。

三、locale:上下文的语言环境。

四、request:(仅在web上下文)的 HttpServletRequest 对象。

五、response:(仅在web上下文)的 HttpServletResponse 对象。

六、session:(仅在web上下文)的 HttpSession 对象。

七、servletContext:(仅在web上下文)的 ServletContext 对象

这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。

// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"

常用的内置方法
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等

二、numbers:数值格式化方法,常用的方法有:formatDecimal等

三、bools:布尔方法,常用的方法有:isTrue,isFalse等

四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等

五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等

六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等

七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等

@{…} 链接表达式

链接表达式好处

不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问

#修改项目名,链接表达式会自动修改路径,避免资源文件找不到
server.context-path=/itdragon

链接表达式结构

无参:@{/xxx}

有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2

引入本地资源:@{/项目本地的资源路径}

引入外部资源:@{/webjars/资源在jar包中的路径}

<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

#{…} 消息表达式
消息表达式一般用于国际化的场景。

~{…} 代码块表达式

支持两种语法结构

推荐:~{templatename::fragmentname}

支持:~{templatename::#id}

templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。

fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment=“fragmentname”

id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式的使用

代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。

th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中。

th:replace:将代码块片段整个替换使用了th:replace的HTML标签中。

th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中。


内容如有帮助,记得点赞哦~
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以很方便的集成 Thymeleaf 模板引擎,下面是整合步骤: 1.添加 Thymeleaf 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2.配置 Thymeleaf 模板 在 `src/main/resources/templates/` 目录下创建一个 thymeleaf 模板文件,例如 index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf Demo</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html> ``` 其中 `${message}` 表示从后台传递过来的数据。 3.配置视图解析器 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: utf-8 ``` 其中: - `cache` 表示是否开启缓存 - `prefix` 表示模板文件所在目录 - `suffix` 表示模板文件后缀 - `encoding` 表示模板文件编码 4.在 Controller 中使用 Thymeleaf 在 Controller 中设置需要传递到前端的数据,并指定要返回的模板文件名: ```java @Controller public class DemoController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 其中: - `@Controller` 表示这是一个控制器 - `@GetMapping("/hello")` 表示处理 GET 请求,路径为 /hello - `Model` 用于存储需要传递到前端的数据 - `return "index"` 表示返回名为 index 的模板文件 5.运行项目 启动 Spring Boot 项目,访问 http://localhost:8080/hello 即可看到效果。 以上就是 Spring Boot 整合 Thymeleaf 的基本步骤,希望能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值