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

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

  • pom文件
  • 后端代码
  • 前端代码
  • 项目结构
  • 渲染效果

pom文件

SpringBoot - thymeleaf 动态填充 html 页面数据_第1张图片

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-thymeleafartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		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>

项目结构

SpringBoot - thymeleaf 动态填充 html 页面数据_第2张图片
注意:如果 index.html 页面没有打包进入 target目录,会报页面找不到的错误,如果没有打包到 target的话,在 pom 文件行添加如下片段

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

SpringBoot - thymeleaf 动态填充 html 页面数据_第3张图片

渲染效果

SpringBoot - thymeleaf 动态填充 html 页面数据_第4张图片

你可能感兴趣的:(#,Java,后端,spring,boot,html,java)