溫馨提示×

springboot配置thymeleaf的方法是什么

小億
89
2023-11-28 02:17:43
欄目: 編程語言

配置Thymeleaf的方法有以下幾步:

  1. 添加Thymeleaf依賴:在pom.xml文件中添加Thymeleaf的依賴配置。例如:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 配置Thymeleaf模板的位置:在application.properties或application.yml文件中添加以下配置項,指定Thymeleaf模板的位置,默認為classpath:/templates/。例如:
spring.thymeleaf.prefix=classpath:/templates/
  1. 配置Thymeleaf緩存:在application.properties或application.yml文件中添加以下配置項,用于配置Thymeleaf的緩存,默認為開啟緩存。例如:
spring.thymeleaf.cache=false
  1. 配置Thymeleaf模板的后綴:在application.properties或application.yml文件中添加以下配置項,指定Thymeleaf模板的后綴,默認為.html。例如:
spring.thymeleaf.suffix=.html
  1. 配置Thymeleaf視圖解析器:在配置類中添加@Bean注解配置Thymeleaf視圖解析器。例如:
@Configuration
public class ThymeleafConfig {
    @Bean
    public ViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        return viewResolver;
    }

    @Bean
    public ITemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    @Bean
    public ITemplateResolver templateResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("templates/");
        templateResolver.setCacheable(false);
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }
}

以上是配置Thymeleaf的基本步驟,根據具體需求可以添加其他配置項。

0