2.SpringBoot利用Thymeleaf实现页面的展示

什么是Thymeleaf?

Thymeleaf是一个现代服务器端Java模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本。

Thymeleaf的主要目标是提供一种优雅且高度可维护的模板创建方式。为实现这一目标,它以自然模板的概念为基础,将其逻辑注入模板文件,其方式不会影响模板被用作设计原型。这改善了设计沟通,缩小了设计和开发团队之间的差距。

Thymeleaf也从一开始就设计了Web标准 - 特别是HTML5 - 允许您创建完全验证的模板,如果您需要的话。

一、配置maven,在pom.xml当中配置

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

二、配置Thymeleaf

.yml配置

XML 复制代码
spring:
   thymeleaf:
       cache: false # 关闭页面缓存
       encoding: UTF-8 # 模板编码
       prefix: classpath:/templates/  # 页面映射路径
       suffix: .html # 试图后的后缀
       mode: HTML5 # 模板模式

.properties配置

XML 复制代码
spring.thymeleaf.prefix=classpath:/templates/

三、新建html页面

四、controller层

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping("/")
    public String index(){
        return "index";
    }
}

五:访问静态资源

在配置文件当中配置 .yml

java 复制代码
spring:
    mvc:
      static-path-pattern: /static/**

引用格式

XML 复制代码
<link rel="stylesheet" href="../static/css/mystyle.css"/>

我们在进行正常访问的时候会报一下的错误,这是因为我们需要给网页标题前添加一个小图标favicon.ico。

我们需要加上这一句话在页面上。

XML 复制代码
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
相关推荐
鹏易灵3 分钟前
C++——2.常量与 const、constexpr 初识详解
java·开发语言·c++
苍何4 分钟前
高考填志愿,我做了个 Skill,300 个 Agent 同时查公司
后端
qq_452396237 分钟前
第十三篇:《K8s 安全基础:RBAC、ServiceAccount、Pod Security》
java·安全·kubernetes
yspwf12 分钟前
NestJS 配置管理完整方案
后端·架构·node.js
雪隐23 分钟前
个人电脑玩AI-03让5060 Ti给你打工——paddleOCR
人工智能·后端
AskHarries30 分钟前
Shell Tool:命令执行、输出读取和长任务管理
后端
张某布响丸辣31 分钟前
Spring AI 极简入门:Java 开发者快速上手 AI 开发
java·人工智能·spring·springai
苍何32 分钟前
开源项目想出海,我让 AI 员工帮我找海外达人
后端
java1234_小锋33 分钟前
请描述 Spring Boot 的启动流程,包括 SpringApplication 的初始化和 run 方法的核心步骤。
java·数据库·spring boot