SpringBoot——SpringBoot 集成 Thymeleaf 模板

目录

1 认识 Thymeleaf

 2  在SpringBoot使用

2.1 创建一个springboot项目

 2.2 在pom.xml文件中会自动添加SpringBoot集成Thymeleaf的起步依赖(剩下的默认配置就中)

2.3 核心配置文件

2.4 写一个controller类

2.5 写一个html页面展示数据


1 认识 Thymeleaf

Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发。

模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎,在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。

Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环
境下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一
样从后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体,
Thymeleaf 要寄托在 HTML 标签下实现。

SpringBoot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来
替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web 开发中,我们往往会选择使用 Jsp 去完成页面的动态渲染,但是 jsp 需要翻译编译运行,效率低。

Thymeleaf 的官方网站:https://www.thymeleaf.org/

Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 2  在SpringBoot使用

2.1 创建一个springboot项目

 

 2.2 在pom.xml文件中会自动添加SpringBoot集成Thymeleaf的起步依赖(剩下的默认配置就中)

<!--        springboot框架集成Thymeleaf起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2.3 核心配置文件

#设置thymeleaf模板引擎的缓存,设置为false关闭,默认是开启
spring.thymeleaf.cache=false

#设置thymeleaf模板引擎的前后缀(可写可不写) 一般都是默认的
spring.thymeleaf.prefix=classpath:/templates/
spring.mvc.view.suffix=.html

2.4 写一个controller类

package com.liuhaiyang.springboot.controller;

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

@Controller
public class UserController {

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("data","springBoot  Thymeleaf");
        return "index";
    }

}

2.5 写一个html页面展示数据

在 src/main/resources 的 templates 下新建一个 index.html 页面用于展示数据

HTML 页面的<html>元素中加入以下属性:<html xmlns:th="http://www.thymeleaf.org">

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${data}">xxx</div>
<h1 th:text="${data}">xxx</h1>
<span th:text="${data}">xxx</span>
</body>
</html>

结果截图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值