SpringBoot - thymeleaf 动态填充 html 页面数据

SpringBoot - thymeleaf 动态填充 html 页面数据

pom文件

在这里插入图片描述

		<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>

后端代码

package com.scd.bootthymeleaf.controller;

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

import java.nio.charset.StandardCharsets;

/**
 * @author James
 * @date 2023/4/2
 */
@Controller
public class IndexController {
    
    

    @GetMapping(value = "/index")
    public String index(Model model) {
    
    
        model.addAttribute("charset", StandardCharsets.UTF_8.name());
        model.addAttribute("title", "标题");
        model.addAttribute("h1", "一级标题");
        model.addAttribute("p", "文本");
        return "index";
    }
}

使用 model 模型增加动态属性值,thymeleaf 默认寻找 .html 的后缀静态页面

前端代码

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <meta th:attr="charset=${charset}">
    <title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${h1}"></h1>
<p th:text="${p}"></p>
</body>
</html>

项目结构

在这里插入图片描述
注意:如果 index.html 页面没有打包进入 target目录,会报页面找不到的错误,如果没有打包到 target的话,在 pom 文件行添加如下片段

		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*</include>
				</includes>
			</resource>
		</resources>

在这里插入图片描述

渲染效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/modelmd/article/details/129918471