Spring Boot(七)--------Thymeleaf模板引擎
16、Thymeleaf
16.1 模板引擎
-
前端交给我们的页面是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等
-
jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的
-
那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢
-
SpringBoot推荐可以使用模板引擎
-
jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的
-
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,就是我们在后台封装的一些数据。然后把模板和数据交给模板引擎,模板引擎按照这个数据把表达式解析、填充到指定的位置,然后把这个数据最终生成一个我们想要的内容写出去,这就是模板引擎,不管是jsp还是其他模板引擎,都是这个思想。
-
不同模板引擎之间,语法有区别。主要来学习一下Spring Boot推荐的Thymeleaf模板引擎,是一个高级语言的模板引擎,语法更简单,功能更强大
16.2 引入Thymeleaf
-
Thymeleaf官网:Thymeleaf
-
Thymeleaf在Github的主页:Github中Thymeleaf主页
-
Spring官方文档:Spring Boot Reference Documentation
-
找到对应的pom依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- Maven会自动下载jar包,可以看到新增了一些关于thymeleaf的jar包
16.3 Thymeleaf分析
- 找一下Thymeleaf的自动配置类:
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";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
/**
* Prefix that gets prepended to view names when building a URL.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Suffix that gets appended to view names when building a URL.
*/
private String suffix = DEFAULT_SUFFIX;
/**
* Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
*/
private String mode = "HTML";
/**
* Template files encoding.
*/
private Charset encoding = DEFAULT_ENCODING;
}
-
可以看到其中默认的前缀后缀,使用Thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可
-
编写一个TestController
@Controller
public class TestController {
@RequestMapping("/test")
public String test(){
return "test";
}
}
- 编写一个test.html放在templates目录下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试</h1>
</body>
</html>
-
访问
localhost:8080/test
,可以得到test.html页面 -
注:使用Thymeleaf,只需要导入对应依赖即可
16.4 Thymeleaf入门
-
参考官方网址的语法!Thymeleaf
-
联系:查出一些数据,在页面中显示
-
修改测试请求,增加数据传输
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","hello,SpringBoot");
return "test";
}
}
- 编写前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试</h1>
<div th:text="${msg}"></div>
</body>
</html>
- 测试成功
16.5 Thymeleaf语法
- 我们可以使用任意的
th:attr
来替换html中原生属性的值 - 一些常见表达式
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:#18
#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.
#uris : methods for escaping parts of URLs/URIs
#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.
==================================================================================
*{...}:选择表达式:和${}在功能上是一样;
#{...}:获取国际化内容
@{...}:定义URL;
~{...}:片段引用表达式
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:
No-Operation: _
- 编写controller,测试转义
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","<h1>hello,SpringBoot</h1>");
return "test";
}
- 编写html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试</h1>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>
- 编写controller,放入一些数据
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","<h1>hello,SpringBoot</h1>");
model.addAttribute("users", Arrays.asList("zzz","mmm"));
return "test";
}
}
- 修改html进行测试
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试</h1>
<!--不转义-->
<div th:text="${msg}"></div>
<!--转义-->
<div th:utext="${msg}"></div>
<!--分隔符-->
<hr>
<!--遍历-->
<div th:each="user:${users}" th:text="${user}"></div>
</body>
</html>