13.模板引擎
模板引擎(jsp,Velocity,FreeMarker,Thymeleaf等)原理:结合模板和数据
springboot推荐使用Thymeleaf:语法简单,功能强大!
使用步骤:
1.引入模板引擎的stater:pom文件中写入配置
<!--引入模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-</artifactId>
</dependency>
切换thymeleaf的版本:pom文件中
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!--布局功能的支持,thymelaf3主程序 -->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
thymeleaf的语法和配置(什么都不需要配置:只需要将html页面放到telmplates文件夹下)
对应的ThymeleafProperties 配置源码如下
@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";
...
}
只要我们将html页面放在classpath:/templates/下,Thymeleaf就能自动渲染
示例如下:
1.控制类代码
@Controller
public class HelloControl {
@RequestMapping("/hello")
public String hello(){
//classpath:/templates/success.html
return "success";
}
}
2.当输入路径:http://localhost:8080/hello,Thymeleaf模板引擎会自动帮我们拼串:去类路径下的/templates/找success.html
thymeleaf参考地址;https://www.thymeleaf.org/
如何给页面传值:
1.在html中导入thymeleaf的名称空间
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">--->导入thymeleaf的名称空间,目的是为有提示功能
<head>
<meta charset="UTF-8">
<title>成功</title>
</head>
<body>
<h1>成功</h1>
<div th:text="${hello}">这是欢迎信息</div>---->取出后台传来的值!
</body>
</html>
2.对应的controler内容:
@Controller
public class HelloControl {
@RequestMapping("/hello")
public String hello(Map<String, Object> map){
map.put("hello","你好!");
//classpath:/templates/success.html
return "success";
}
}
页面输出:
语法规则:
th:text:改变当前元素中的文本内容
th:任意的html属性;来替换原生属性的值
示例:
<div id="div-1" class="mydiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是欢迎信息</div>
th的语法和jsp的类比如下:
表达式语法:
Simple expressions:
1.Variable Expressions: ${...}获取变量值;底层式OGNL
1).获取对象的属性、调用方法
2).使用内置的基本对象:如下
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
3.内置的一些工具对象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
Page 20 of 106#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
2.Selection Variable Expressions: *{...}:变量的选择表达式,和${}的功能一致,多了一项功能:配合th:object使用
示例:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
相当于:
<div>
<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>
3.Message Expressions: #{...}:获取国际化内容
4.Link URL Expressions: @{...}:定义url连接:
用法示例:@{/order/process(execId=${execId},execType='FAST')}
相当于href超链接:
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
5.Fragment Expressions: ~{...}片段以用表达式
示例:
<div th:insert="~{commons :: main}">...</div>
Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations:(布尔运算)
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:(条件运算)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
Page 17 of 106No-Operation: _
示例:测试遍历等
控制类:
@Controller
public class HelloControl {
@RequestMapping("/hello")
public String hello(Map<String, Object> map){
map.put("hello","<h1>你好!</h1>");
map.put("user", Arrays.asList("张三","李四","王五"));
//classpath:/templates/success.html
return "success";
}
}
页面html:
<!--不会转义特殊字符:后台传的<h1>你好!</h1>标签会作为字符串-->
<div th:text="${hello}"></div>
<!--转义特殊字符:后台传的<h1>你好!</h1>标签会起作用-->
<div th:utext="${hello}"></div>
<!--th:each每次遍历都会生成当前的这个标签:3个h4-->
<h4 th:text="${userText}" th:each="userText:${user}"></h4>
<hr>
<h4>
<span th:each="userText:${user}">
<!--
内容也可以不写在标签上,而写在标签里
[[代表的是转义特殊字符:作为字符串]]====和th:text一样
[(代表的是不转义特殊字符:标签起作用)]====和th:utext一样
-->
[[${userText}]]
</span>
</h4>
页面如下: