117.info
人生若只如初见

Spring Boot如何整合Thymeleaf模板引擎

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

  1. 添加依赖

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


    org.springframework.boot
    spring-boot-starter-thymeleaf

  1. 配置Thymeleaf

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

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

或者使用YAML格式:

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

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




    Title


    

Hello, World!

  1. 编写Controller

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

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

@Controller
public 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";
    }
}
  1. 运行应用程序

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

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

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe894AzsPCQNRBg.html

推荐文章

  • Spring Boot怎么使用yml格式进行配置

    要使用yml格式进行配置,需要按照以下步骤进行操作: 在Spring Boot项目的资源文件夹(src/main/resources)下创建一个名为application.yml的文件。 在applicati...

  • Spring Boot使用yml格式进行配置的方法

    Spring Boot使用yml格式进行配置的方法分为以下几个步骤: 在项目的src/main/resources目录下创建一个名为application.yml的文件。 在application.yml文件中使用...

  • spring boot是什么

    Spring Boot是一个用于简化Spring应用程序开发的框架。它提供了一种快速启动和配置Spring应用程序的方式,以便开发者可以更加专注于业务逻辑的实现而不需要过多关...

  • spring boot自动配置的原理是什么

    Spring Boot的自动配置原理是基于条件注解和Spring的条件注解机制实现的。
    在Spring Boot中,自动配置是通过在类上使用@Conditional注解来进行条件判断的。...

  • Spring Boot中如何优化synchronized的使用

    在Spring Boot中,优化synchronized的使用可以通过以下几种方法实现: 使用java.util.concurrent包中的并发工具类:Java提供了许多高级的并发工具类,如Reentran...

  • 使用synchronized时Spring Boot应用的性能监控

    在Spring Boot应用中,使用synchronized关键字可能会导致性能问题,因为它会限制同一时间只有一个线程能够访问同步代码块。为了监控这种情况对应用性能的影响,你...

  • Spring Boot中synchronized与volatile的区别

    在Java中,synchronized和volatile是两种不同的线程同步机制,它们各自有自己的特点和适用场景。在Spring Boot中,这些概念同样适用。 synchronized:
    sync...

  • 如何在Spring Boot中使用synchronized实现分布式锁

    在Spring Boot中,我们可以使用synchronized关键字来实现分布式锁。但是,这种方法并不是最佳实践,因为它只能在单个JVM中工作。为了在分布式系统中实现分布式锁...