Spring Boot如何整合Thymeleaf模板引擎

   2024-09-30 5400
核心提示:要在Spring Boot中整合Thymeleaf模板引擎,请按照以下步骤操作:添加依赖在pom.xml文件中添加Thymeleaf的依赖。将以下代码添加到

要在Spring Boot中整合Thymeleaf模板引擎,请按照以下步骤操作:

添加依赖

在pom.xml文件中添加Thymeleaf的依赖。将以下代码添加到<dependencies>标签内:

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

在application.properties或application.yml文件中添加Thymeleaf的配置。以下是一些常用的配置选项:

# application.propertiesspring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.cache=falsespring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML

或者使用YAML格式:

# application.ymlspring:  thymeleaf:    prefix: classpath:/templates/    suffix: .html    cache: false    encoding: UTF-8    mode: HTML
创建模板文件

在src/main/resources/templates目录下创建Thymeleaf模板文件。例如,创建一个名为index.html的文件:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>    <title th:text="${title}">Title</title></head><body>    <h1 th:text="${message}">Hello, World!</h1></body></html>
编写Controller

创建一个Spring MVC控制器,用于处理请求并返回Thymeleaf模板。例如:

import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;@Controllerpublic class MyController {    @GetMapping("/")    public String index(Model model) {        model.addAttribute("title", "Thymeleaf Integration");        model.addAttribute("message", "Welcome to Thymeleaf integration with Spring Boot!");        return "index";    }}
运行应用程序

启动Spring Boot应用程序,然后在浏览器中访问http://localhost:8080/。你应该能看到Thymeleaf模板引擎渲染的页面。

这就是在Spring Boot中整合Thymeleaf模板引擎的方法。现在你可以开始使用Thymeleaf来构建动态HTML页面了。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号