SpringBoot - thymeleaf dynamically populates html page data

SpringBoot - thymeleaf dynamically populates html page data

pom file

insert image description here

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

backend code

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";
    }
}

Use the model model to add dynamic attribute values, and thymeleaf looks for static pages with the suffix of .html by default

front-end code

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

project structure

insert image description here
Note: If the index.html page is not packaged into the target directory, an error that the page cannot be found will be reported. If it is not packaged into the target, add the following fragment to the pom file line

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

insert image description here

rendering effect

insert image description here

Guess you like

Origin blog.csdn.net/modelmd/article/details/129918471