Thymeleaf配置
时间: 2024-05-02 16:22:17 浏览: 68
Thymeleaf配置主要包括以下几个方面:
1. 引入Thymeleaf依赖:在项目的pom.xml文件中添加Thymeleaf相关的依赖,例如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 配置Thymeleaf模板引擎:在Spring Boot的application.properties文件中配置Thymeleaf模板引擎相关属性,例如:
```properties
# 配置Thymeleaf模板引擎
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
```
3. 配置Thymeleaf视图解析器:在Spring Boot的配置类中配置Thymeleaf视图解析器,例如:
```java
@Configuration
public class ThymeleafConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
}
```
其中,templateResolver方法配置了Thymeleaf模板引擎的相关属性;templateEngine方法配置了模板引擎,并将模板解析器注入到模板引擎中;viewResolver方法配置了Thymeleaf视图解析器,并将模板引擎注入到视图解析器中。通过这些配置,就可以使用Thymeleaf模板引擎了。
阅读全文