弹簧引导实战之模板引擎

  

虽然现在很多开发,都采用了前后端完全分离的模式,即后端只提供数据接口,前端通过AJAX请求获取数据,完全不需要用的模板引擎。这种方式的优点在于前后端完全分离,并且随着近几年前端工程化工具和MVC框架的完善,使得这种模式的维护成本相对来说也更加低一点。但是这种模式不利于搜索引擎优化,并且在性能上也会稍微差一点,还有一些场景,使用模板引擎会更方便,比如说邮件模板。这篇文章主要讨论弹簧引导与模板引擎Thymeleaf, Freemaker以及JSP的集成。

  

  

第一步:引入jar包(thymeleaf对应的起动器):

        & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-thymeleaf   & lt;/dependency>      

第二步:配置thymeleaf:

        春天:   thymeleaf:   前缀:类路径://模板   check-template-location:真   缓存:假   后缀:. html   utf - 8编码:   内容类型:text/html   模式:HTML5      

前缀:指定模板所在的目录

  

check-tempate-location:检查模板路径是否存在

  

缓存:是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为真,可以提高性能。

  

encoding&内容类型:这个大家应该比较熟悉了,与Servlet中设置输出对应属性效果一致。

  

模式:这个还是参考官网的说明吧,并且这个是2.倍与3.0不同,本文自动引入的包是2.15 .

  

第三步编写thymeleaf模板文件:

        & lt; !DOCTYPE HTML>   & lt; html xmlns=" http://www.w3.org/1999/xhtml " xmlns: th=" http://www.thymeleaf.org "比;   & lt; head>   & lt;元内容=" text/html; charset=utf - 8”/比;   & lt;/head>   & lt; body>   & lt; h7> Thymeleaf模板引擎& lt;/h7>      & lt;表边界=?”背景=" # f0ffff "比;   & lt; thead>   & lt; tr>   & lt; th>序号& lt;/th>   & lt; th>标题& lt;/th>   & lt; th>摘要& lt;/th>   & lt; th>创建时间& lt;/th>   & lt;/tr>   & lt;/thead>   & lt; tbody th:每个="文章:${列表}”在   & lt; tr>   & lt; td th:文本=" $ {article.id} "祝辞& lt;/td>   & lt; td th:文本=" $ {article.title} "祝辞& lt;/td>   & lt; td th:文本=" $ {article.summary} "祝辞& lt;/td>   & lt; td th:文本=" $ {article.createTime} "祝辞& lt;/td>   & lt;/tr>   & lt;/tbody>   & lt;/table>   & lt;/body>   & lt;/html>      

大家可以看的到,thymeleaf还是比较简单的,并且最大的特点就是的标签是作为HTML元素的属性存在的,也就是说,该页面是可以直接通过浏览器来预览的,只是没有数据而已,这个很方便大家进行调试。

  

第四步配置控制器:

        @ controller   @RequestMapping(文章“/?   公开课ArticleController {   @ autowired   私人ArticleService ArticleService;合并合并      @RequestMapping ("/articleList.html”)   公共字符串getArticleList(模型模型,字符串标题,@RequestParam (defaultValue=" https://www.yisu.com/zixun/10 ")整数页大小,   @RequestParam (defaultValue=" https://www.yisu.com/zixun/1 ")整数pageNum) {   int抵消=(pageNum - 1) *页大小的影响;   List
列表=articleService。合并getArticles(标题1 l,抵消,页大小);   模型。addAttribute(“名单”,名单);   返回“文章/articleList”;   }   }      

注意,这里用的注解是@ controller,而不是@RestController,因为@RestController会自动将返回结果转为字符串。

  

第五步查看结果

  

春天引导实战之模板引擎

  

  

1,引入jar包(Freemarker对应的起动器)

        & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-freemarker   & lt;/dependency>之前      

2,配置freemarker:

        春天:   freemarker):   template-loader-path:类路径://模板   后缀:.ftl   内容类型:text/html   utf - 8字符集:   设置:   number_format:“0。# #”      

除了设置外,其他的配置选项和thymeleaf类似.settings会对freemarker的某些行为产生影响,如日期格式化,数字格式化等,感兴趣的同学可以参考官网提供的说明:https://freemarker.apache.org/docs/api/freemarker/template/Configuration.html setSetting-java.lang.String-java.lang.String——

弹簧引导实战之模板引擎