SpringBoot开发——结合Thymeleaf模板整合HTML

发布于:2024-09-18 ⋅ 阅读:(13) ⋅ 点赞:(0)

一、 Thymeleaf介绍

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。开发者只需将标签属性添加到模板中,接下来这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

更多介绍详见:Tutorial: Using Thymeleaf

二、Springboot整合thymeleaf模板

Spring Boot可以结合Thymeleaf模板来整合HTML,使用原生的HTML作为视图。

1、实现步骤

1)创建一个Springboot项目

在这里插入图片描述
选择依赖:“Spring Web” 和“Thymeleaf”
在这里插入图片描述
项目创建后,目录结构如下:
在这里插入图片描述

2) 创建application.yml文件

删除文件application.properties,建文件application.yml,配置内容如下:

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html

3)创建HTML文件

在templates目录下,建文件index.html
修改后如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>templates</title>
</head>
<body>
<p th:text="${hello}"></p>
</body>
</html>

4)编写controller文件

创建包com.demo.thymeleaf.controller,在com.demo.thymeleaf.controller下创建controller类HelloController,内容如下:

package com.demo.thymeleaf.controller;

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

@Controller
public class HelloController {
   

    @GetMapping("/hello")
    public String Hello(Model model){
   
        model.addAttribute("hello", "hello Thymeleaf");
        return "index";
    }
}

现在目录结构如下:
在这里插入图片描述

5)启动Spring Boot

启动后,浏览器输入:http://localhost:8080/hello
在这里插入图片描述

温馨提示:如果希望客户端可以直接访问HTML资源,将这些资源放置在static路径下即可,否则必须通过controller的后台映射才可以访问静态资源。

2、Thymeleaf常用语法

赋值、拼接

@GetMapping("/index")
    public String index(Map<String, String> map){
   
        map.put("name","张三");
        return "index";
    }
<p th:text="${name}"></p>
<p th:text="'学生姓名是:'+${name}+'。'"></p>
<p th:text="|学生姓名是,${name}|"></p