Thymeleaf与Spring Boot的整合
时间: 2023-08-23 15:18:13 浏览: 145
Thymeleaf与Spring Boot的整合非常简单,只需要在pom.xml中添加Thymeleaf的依赖,然后在Spring Boot的配置类中添加Thymeleaf的配置即可。
以下是一个简单的Thymeleaf和Spring Boot的整合示例:
1.在pom.xml文件中添加Thymeleaf的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2.在Spring Boot的配置类中添加Thymeleaf的配置:
```
@Configuration
public class ThymeleafConfig {
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
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;
}
}
```
3.创建一个Thymeleaf模板:
在src/main/resources/templates目录下创建一个名为"index.html"的文件,并添加以下内容:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello Thymeleaf</title>
</head>
<body>
<h1 th:text="'Hello ' + ${name} + '!'" />
</body>
</html>
```
4.创建一个Spring Boot控制器:
```
@RestController
public class MyController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "World");
return "index";
}
}
```
5.运行应用程序:
现在可以运行应用程序,并访问http://localhost:8080/,应该可以看到一个包含"Hello World!"的页面。在这个示例中,Thymeleaf的模板引擎将"Hello World!"渲染到了模板中的h1元素中。
阅读全文