- 改文章项目文件结构图如下:
步骤一:创建工程、添加依赖
<dependencies>
<!-- thymeleaf相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web项目依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
步骤二:配置thymeleaf,部分常见配置如下:
#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=false
#是否检查模板是否存在,默认为true
spring.thymeleaf.check-template=true
#是否检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true
#模板文件编码
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件后缀
spring.thymeleaf.suffix=.html
步骤三:配置控制器
- 首先配置实体类Book.java
package cn.aju.study;
public class Book {
private Integer id;
private String name;
private String author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
然后再BookController 中返回ModelAndView,代码如下:
package cn.aju.study;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
@GetMapping("/books")
public ModelAndView books() {
List<Book> books = new ArrayList<Book>();
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("罗贯中");
b1.setName("三国演义");
books.add(b1);
Book b2 = new Book();
b2.setId(2);
b2.setAuthor("曹雪芹");
b2.setName("红楼梦");
books.add(b2);
ModelAndView mv = new ModelAndView();
mv.addObject("books", books);
//设置视图显示位置与模板名称
mv.setViewName("test/demo");
return mv;
}
}
第四步:创建视图:demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>books</title>
</head>
<body>
<div>找到了test目录下的demo页面</div>
<div>遍历ModelANdView中的books数据</div>
<table border="1">
<tr>
<td>图书编号</td>
<td>图书名称</td>
<td>图书作者</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
</tr>
</table>
</body>
</html>
- xmlns:th:表示导入Thymeleaf的名称空间,这样在Idea中使用Thymeleaf语法将不会报错
步骤五:我们运行之后的显示结果如下图所示