springboot使用Thymeleaf

Thymeleaf

Thymeleaf是当今比较流行的模板框架,并且是Spring Boot官方推荐使用的模板框架。本小节介绍Spring Boot框架如何使用Thymeleaf,并且会对Thymeleaf框架的使用方法进行介绍。

首先创建项目,在项目中加入spring-boot-starter-thymeleaf依赖。这里需要提醒的是,由于Thymeleaf对HTML的校验特别严格,比如标签没有结束等可能会对不熟悉者造成未知的困惑,因此我们还需要加入nekohtml的依赖来避免这个“坑”。Thymeleaf依赖如代码

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        取出html严格校验-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
        </dependency>

完成依赖的配置之后,我们需要在配置文件中对Thymeleaf进行配置,比如编码格式、缓存设置、文件前后缀等。配置文件内容如代码

server.port=8089
#缓存是否开启,开发时建议关闭
spring.thymeleaf.cache=false
#编码格式
spring.thymeleaf.encoding=UTF-8
#thymeleaf对html的校验很严格,用这个去除严格校验
spring.thymeleaf.mode=LEGACYHTML5
#模板文件前缀
spring.thymeleaf.prefix=classpath:/templates/
#模板文件后缀
spring.thymeleaf.suffix=.html



到这里,准备工作已经完成。需要做的是创建一个Controller和HTML进行测试。新建一个IndexController,我们先写一个简单的路由跳转方法并且传一个字符串值进行测试。IndexController内容如代码

package com.shrimpking.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/12/21 10:18
 */
@Controller
public class IndexController
{
    @GetMapping("/")
    public String index(ModelMap modelMap){
        modelMap.addAttribute("msg","hello, thymeleaf");
        return "index";
    }
}

然后,在src/mian/resources/templates下新建一个index.html(需要结合配置文件中spring.thymeleaf.prefix的配置信息存放HTML),使用th:text="${msg}"来接收后台传来的数据。index.html内容如代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>

启动项目,在浏览器上访问http://localhost:8089,可以看到有如下显示:

其实到这里Spring Boot整合Thymeleaf已经完成,但是为了方便后面章节的使用,笔者在这里再介绍一下Thymeleaf模板的常用语法。

th:text 设置当前元素的文本内容。

• th:value 设置当前元素的值。

• th:each 循环遍历元素,一般配合上面两者使用。

• th:attr 设置当前元素的属性。

• th:if th:switch th:case th:unless 用作条件判断。

• th:insert th:replace th:incloud 代码块引入,一般用作提取公共文件,或者引用公共静态文件等。

当然,Thymeleaf也提供了一些内置方法供我们使用,比如:

• #numbers 数字方法。

• #dates 日期方法。

• #calendars 日历方法。

• #strings 字符串方法。

• #lists 集合方法。

• #maps 对象方法。

关于Thymeleaf先了解到这里,后面的章节会对它有具体的实战使用,这里就不再赘述了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值