前端模板引擎技术的出现,使得前端开发人员无需关注后端业务的具体实现,只关注自己的页面呈现效果即可。并且解决了前端代码错综复杂的问题,实现了前后端分离开发。SpringBoot框架对很多常用的模板引擎技术提供了整合支持,比如FreeMarker、Thymeleaf、Mustache等。SpringBoot不太支持JSP模板。

5.1 整合Thymeleaf

5.1.1 常用语法

在HTML页面上使用Thymeleaf标签,能够动态的替换掉静态内容,使页面静态展示。

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head>
  3. <meta charset="UTF-8">
  4. <link rel="stylesheet" type="text/css" media="all"
  5. href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  6. <title>Title</title>
  7. </head> <body>
  8. <p th:text="${hello}">欢迎进入Thymeleaf学习</p>
  9. </body>
  10. </html>

上述代码中,“xmlns:th=”http://www.thymeleaf.org”用来引入Thymeleaf模板引擎标签,
关键字“th”标注标签是thymeleaf模板引擎提供的标签,以下是常用标签:

th:标签 说明
th:insert 布局标签,替换内容到引入的文件
th:replace 页面片段包含(类似于JSP的include标签)
th:each 元素遍历
th:if 条件判断,如果为真
th:unless 条件判断,如果为假
th:switch 条件判断,进行选择性匹配
th:case 条件判断,进行选择性匹配
th:value 属性值修改,指定标签属性值
th:href 用于设定链接地址
th:src 用于设定链接地址
th:text 用于指定标签的文版内容

标准表达式

说明 表达式语法
变量表达式 ${…}
选择变量表达式 *{…}
消息表达式 #{…}
链接URL表达式 @{…}
片段表达式 ~{…}

5.1.2 基本使用

  1. 首先引入Thymeleaf的启动依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
    4. </dependency>
  2. 在配置文件中进行配置

    1. #启动模板缓存,默认为true,开发过程通常设为false,上线设为true
    2. spring.thymeleaf.cache = true
    3. spring.thymeleaf.encoding = UTF-8
    4. spring.thymeleaf.mode = HTML5
    5. #指定模板的存放路径,默认为classpath:/templates/
    6. spring.thymeleaf.prefix = classpath:/templates/
    7. #指定模板页面后缀
    8. spring.thymeleaf.suffix = .html
  3. 静态资源的访问,SpringBoot默认会查找resources目录下的public、resources、static文件夹。

  4. 编写html页面,web控制器进行跳转。页面示例:
    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1,shrink- to-fit=no">
    6. <title>用户登录界面</title>
    7. <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    8. <link th:href="@{/login/css/signin.css}" rel="stylesheet">
    9. </head> <body class="text-center">
    10. <!-- 用户登录form表单 -->
    11. <form class="form-signin">
    12. <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
    13. <h1 class="h3 mb-3 font-weight-normal">请登录</h1>
    14. <input type="text" class="form-control" th:placeholder="用户名" required="" autofocus="">
    15. <input type="password" class="form-control" th:placeholder="密码" required="">
    16. <div class="checkbox mb-3">
    17. <label> <input type="checkbox" value="remember-me"> 记住我 </label>
    18. </div>
    19. <button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button>
    20. <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p>
    21. </form>
    22. </body>
    23. </html>