如何在Spring MVC中使用Thymeleaf模板引擎展示数据?
时间: 2024-09-28 18:06:36 浏览: 52
在Spring MVC中使用Thymeleaf模板引擎展示数据需要几个步骤:
1. **添加依赖**:
- 添加Thymeleaf依赖到你的Maven或Gradle构建文件。例如,在pom.xml中:
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. **配置模板引擎**:
- 在application.properties或application.yml中启用Thymeleaf,并指定模板文件的位置:
```properties
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=/templates/
spring.thymeleaf.suffix=.html
```
3. **创建视图解析器**:
- 在Spring MVC配置类(通常是@Configuration class)中,添加ThymeleafViewResolver:
```java
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
private TemplateEngine templateEngine() {
TemplateEngine engine = new TemplateEngine();
engine.setEnableSpringELIntegration(true);
return engine;
}
```
4. **生成视图**:
- 当你需要从Controller返回一个渲染后的页面时,可以在`ModelAndView`对象中指定数据和视图名称。例如:
```java
@GetMapping("/example")
public ModelAndView showExample(Model model) {
List<Music> musics = musicService.getAllMusics();
model.addAttribute("musics", musics); // 将数据添加到模型
return new ModelAndView("example", "model", model);
}
```
其中"example"是你的Thymeleaf模板文件名,"model"是你在模板中使用的变量前缀。
5. **创建模板**:
- 在指定的目录(如src/main/resources/templates)下创建HTML文件,例如`example.html`。在其中使用Thymeleaf语法插入数据:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<table>
<tr th:each="music : ${model.musics}">
<td th:text="${music.name}"></td>
<!-- 更多表格内容... -->
</tr>
</table>
</body>
</html>
```
现在当你访问相应的路径时,Thymeleaf会将数据填充到模板中显示。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)