Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据产看显示效果。同时,Spring boot提供了Thymeleaf自动化配置解决方案,因此在Spring boot中使用Thymeleaf非常方便。Spring boot整合Thymeleaf步骤如下:
1、新建一个Spring boot项目,在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、配置Thymeleaf
Spring boot提供了Thymeleaf自动化配置类ThymeleafProperties
@Component
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
}
默认的模板位置在classpath:/templates/,默认的模板后缀为.html。
以下为开发者对默认的Thymeleaf配置参数进行自定义配置,在application.properties中进行配置,如下:
#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=true
#检查模板是否存在,默认为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
3、配置实体类
public class BookEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String author;
省略getter/setter
}
4、配置控制类
@RestController
public class BookController {
@GetMapping("/books")
public ModelAndView books() {
List<BookEntity> books = new ArrayList<>();
BookEntity b1 = new BookEntity();
b1.setId(1);
b1.setAuthor("罗贯中");
b1.setName("三国演义");
BookEntity b2 = new BookEntity();
b2.setId(2);
b2.setAuthor("曹雪芹");
b2.setName("红楼梦");
books.add(b1);
books.add(b2);
ModelAndView mv = new ModelAndView();
mv.addObject("books",books);
mv.setViewName("books");
return mv;
}
}
5、创建视图
在resources目录下的templates目录中创建books.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
<table border="1">
<tr>
<td>图书编号</td>
<td>图书名称</td>
<td>图书作者</td>
</tr>
<!--/*@thymesVar id="books" type="mapper"*/-->
<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>
6、运行
在浏览器中访问地址http://localhost:8080/books