五、视图解析与模板引擎
- SpringBoot默认不支持jsp,需要引入第三方模板引擎技术实现页面渲染
1、Thymeleaf简介
-
现代化、服务端Java模板引擎
-
在SpringBoot中的使用
-
引入starter(场景启动器)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
SpringBoot中已经规定好了前缀和后缀temlates文件夹下
-
在html文件中要引入名词空间:
xmlns:th="http://www.thymeleaf.org"
-
2、表达式
表达式名称 | 语法 | 描述 |
---|---|---|
变量取值 | ${xxx} | 获取请求域、Session域、对象中的数据 |
选择变量 | *{xxx} | 获取上下文对象值 |
消息 | #{xxx} | 获取国际化等值 |
链接 | @{xxx} | 生成链接 |
片段表达式 | ~{xxx} | 相当于jsp:include作用,引入公共页面片段 |
3、字面量
- 文本值使用单引号
- 空值使用 null
4、文本操作
- 字符串拼接 +
- 变量替换 The name is ${name}
5、布尔运算
- 运算符: and or
- 一元运算: ! , not
6、比较运算符
- > , < , >= , <= ( gt , lt , ge , le **)**等式: == , != ( eq , ne )
7、迭代
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
8、判断
-
th:if
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
-
th:switch
<div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </div>
9、行内写法
- [[${session.loginUser.userName}]]
- 使用[[]]可以离开标签的束缚
10、抽取公共部分
-
<body> <div th:insert="footer :: copy"></div> <div th:replace="footer :: copy"></div> <div th:include="footer :: copy"></div> </body>
-
<body> <div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> </div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> <div> © 2011 The Good Thymes Virtual Grocery </div> </body>
11、视图解析原理
- 目标方法处理的过程中,所有的数据都会被放在ModelAndViewContainer中,包括数据和视图地址
- 方法的参数是一个自定义类型对象(从请求参数中确定),把他重新放在ModelAndViewContainer中
- 任何目标方法执行完成之后都会返回ModelAndView(数据和视图地址)
- processDispatchResult 处理派发结果(页面如何响应)
- render(mv,request,response) : 进行页面的渲染逻辑
- 根据方法的String返回值得到View对象[定义了页面的渲染逻辑]
- 所有的输入解析器尝试是否能根据当前返回值得到View对象
- 得到了 redirect:/main --> Thymeleaf new RedirectView()
- ContentNegotiationViewResolver藜麦那包含了下面所有的属兔解析器,内部还是利用下面所有的视图解析得到的视图对象
- view.render(mv,getModelInternal(),request,response) : 视图对象调用自定义的render进行页面渲染工作
- RedirectView : 如何渲染[重定向到一个页面]
- 获取目标url地址
- response.sendRedirect(encodedURL)
- RedirectView : 如何渲染[重定向到一个页面]
- 根据方法的String返回值得到View对象[定义了页面的渲染逻辑]
- render(mv,request,response) : 进行页面的渲染逻辑
-
视图解析:
-
返回值以forward: 开始 : new InternalResourceView(forwardUrl) --> 转发
request.getRequestDispatcher(path).forward(request,response)
-
返回值以 redirect: 开始 :new RedirectView() --> render就是重定向
-
返回值是普通字符串 :new ThymeleafView()
-