虽然现在很多开发,都采用了前后端完全分离的模式,即后端只提供数据接口,前端通过AJAX请求获取数据,完全不需要用的模板引擎。这种方式的优点在于前后端完全分离,并且随着近几年前端工程化工具和MVC框架的完善,使得这种模式的维护成本相对来说也更加低一点。但是这种模式不利于SEO,并且在性能上也会稍微差一点,还有一些场景,使用模板引擎会更方便,比如说邮件模板。这篇文章主要讨论Spring boot与模板引擎Thymeleaf、Freemaker以及JSP的集成。
一、集成Thymeleaf
第一步:引入jar包(thymeleaf对应的starter):
| 1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
第二步:配置thymeleaf:
| 1 2 3 4 5 6 7 8 9 |
spring: thymeleaf: prefix: classpath:/templates/ check-template-location: true cache: false suffix: .html encoding: UTF-8 content-type: text/html mode: HTML5 |
prefix:指定模板所在的目录
check-tempate-location: 检查模板路径是否存在
cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
encoding&content-type:这个大家应该比较熟悉了,与Servlet中设置输出对应属性效果一致。
mode:这个还是参考官网的说明吧,并且这个是2.X与3.0不同,本文自动引入的包是2.15。
第三步 编写thymeleaf模板文件:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta content="text/html;charset=UTF-8"/> </head> <body> <h6>Thymeleaf 模板引擎</h6> <table border="1" bgcolor="#f0ffff"> <thead> <tr> <th>序号</th> <th>标题</th> <th>摘要</th> <th>创建时间</th> </tr> </thead> <tbody th:each="article : ${list}"> <tr> <td th:text="${article.id}"></td> <td th:text="${article.title}"></td> <td th:text="${article.summary}"></td>
|