springboot thymeleaf 的配置

springboot 文章 2023-04-17 13:51 1989 0 全屏看文

AI助手支持GPT4.0

要在 Spring Boot 应用程序中使用 Thymeleaf 模板引擎,您需要执行以下步骤:


在 pom.xml 或 build.gradle 中添加 Thymeleaf 和 Spring Boot Starter Thymeleaf 的依赖项。例如,在 Maven 中,您可以将以下依赖项添加到 pom.xml 文件中:

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


在 application.properties 或 application.yml 中配置 Thymeleaf 属性。例如,在 application.properties 文件中,您可以设置以下属性:

spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

这些属性控制了 Thymeleaf 模板引擎的缓存、模式、编码、模板文件夹前缀和后缀等行为。


创建一个包含 Thymeleaf 模板的 HTML 文件,并将其放置在 resources/templates 目录下(或根据前面的配置属性所指定的模板文件夹)。例如,创建一个名为 "index.html" 的模板文件,其中包含以下内容:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Template</title>
</head>
<body>
    <h1 th:text="${title}">Title</h1>
    <p th:text="${content}">Content</p>
</body>
</html>


创建一个 Spring MVC 控制器,将模型数据填充到 Thymeleaf 模板中。例如:

@Controller
public class MyController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("title", "Hello, Thymeleaf!");
        model.addAttribute("content", "Welcome to my Thymeleaf template.");
        return "index";
    }
}

在这个例子中,我们通过 model 参数向 Thymeleaf 模板中传递了两个变量:"title" 和 "content"。


运行应用程序,并访问 http://localhost:8080/ 查看 Thymeleaf 模板渲染的效果。


这就是使用 Spring Boot 和 Thymeleaf 的基本配置和使用方法。当然,根据您的实际需求、场景和功能,可能需要更复杂的配置和使用方式。

-EOF-

AI助手支持GPT4.0


国内超级便宜服务器

摸鱼人热门新闻聚合

钻级赞助商 我要加入

开发者在线工具

第三方支付技术请加QQ群

相关文章
springboot thymeleaf 的配置
spring里使用静态方法获取HttpServeltRequest
spring boot 调用 redis的两种方法
SpringBoot里有多少种 ContextHolder 有分别有啥用
spring项目输出当前的activeprofile
随便看看
微信开放平台跟公众平台有什么区别? 3517
怎么添加小程序支付功能? 4311
教育科技公司申请微信支付被拒绝? 4694
微信公众号免300认证教程 5775
小程序已经上线,作为管理员无法在小程序数据助手查看数据? 5186
小程序广告组件通过审核,但是小程序内没有显示广告? 4961
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9389
问题? 8909
如何快速搭建抽奖助手小程序(无需代码知识) 6039
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7343