Java:SpringBoot 整合 Thymeleaf模板引擎渲染html

依赖

<
    dependency>
    
    <
    groupId>
    org.springframework.boot<
    /groupId>
    
    <
    artifactId>
    spring-boot-starter-thymeleaf<
    /artifactId>
    
<
    /dependency>
    

完整依赖 pom.xml

<
    ?xml version="1.0" encoding="UTF-8"?>
    
<
    project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <
    modelVersion>
    4.0.0<
    /modelVersion>
    
    <
    parent>
    
        <
    groupId>
    org.springframework.boot<
    /groupId>
    
        <
    artifactId>
    spring-boot-starter-parent<
    /artifactId>
    
        <
    version>
    2.7.7<
    /version>
    
        <
    relativePath/>
     <
    !-- lookup parent from repository -->
    
    <
    /parent>
    

    <
    groupId>
    com.example<
    /groupId>
    
    <
    artifactId>
    demo<
    /artifactId>
    
    <
    version>
    0.0.1-SNAPSHOT<
    /version>
    
    <
    name>
    demo<
    /name>
    
    <
    description>
    Demo project for Spring Boot<
    /description>
    
    <
    properties>
    
        <
    java.version>
    1.8<
    /java.version>
    
    <
    /properties>
    

    <
    dependencies>
    
        <
    dependency>
    
            <
    groupId>
    org.springframework.boot<
    /groupId>
    
            <
    artifactId>
    spring-boot-starter-web<
    /artifactId>
    
        <
    /dependency>
    

        <
    dependency>
    
            <
    groupId>
    org.springframework.boot<
    /groupId>
    
            <
    artifactId>
    spring-boot-starter-thymeleaf<
    /artifactId>
    
        <
    /dependency>
    

        <
    dependency>
    
            <
    groupId>
    org.springframework.boot<
    /groupId>
    
            <
    artifactId>
    spring-boot-devtools<
    /artifactId>
    
            <
    scope>
    runtime<
    /scope>
    
            <
    optional>
    true<
    /optional>
    
        <
    /dependency>
    
    <
    /dependencies>
    
<
    /project>
    

控制器

package com.example.demo.controller;
    


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


@Controller
public class IndexController {


    @GetMapping("/")
    public String index(Model model) {
    
        model.addAttribute("name", "Tom");
    
        return "index";

    }

}
    

模板文件 resources/templates/index.html

<
    !doctype html>
    

<
    !-- 导入thymeleaf的名称空间 -->
    
<
    html lang="zh" xmlns:th="http://www.thymeleaf.org">
    
    <
    body>
    
        <
    h2>
    hello <
span th:text="${
name}
    ">
    <
    /span>
    !<
    /h2>
    
    <
    /body>
    
<
    /html>
    

显示结果

参考

Spring Boot——Thymeleaf