web开发--thymeleaf模板引擎
1、thymeleaf模板引擎
前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢?
SpringBoot推荐你可以来使用模板引擎:
模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,什么样一个思想呢我们来看一下这张图:
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
2、如何引入Thymeleaf
Thymeleaf 博客:https://www.cnblogs.com/msi-chen/p/10974009.html
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
方式一
1、打开spring启动器的官方文档,找到thymeleaf启动器
2、在项目中引入thymeleaf依赖
找到spring官网关于thymeleaf的启动器maven坐标
3、在项目pom文件中引入thymeleaf坐标
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
方式二
我们可以直接在项目的pom文件中引入thymeleaf启动器坐标
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
查看maven:已成功引入坐标
3、怎样通过控制层跳转到html页面
找到ThymeleafProperties类,我们可以看到要想从控制层跳转到html页面,则html页面需要满足以下条件:
1、html页面需要放置在类路径下的templates文件夹下
2、html页面后缀必须为.html
4、使用thymeleaf模板引擎开发案例
1、编写控制层
//templates目录下所有的页面,只能通过controller来跳转! 这个需要模板引擎的支持:thymeleaf
@Controller
public class IndexController {
@RequestMapping("/test")
public String Index(Model model){
//存入数据
model.addAttribute("msg","hello springboot");
//classpath:/templates/test.html
return "test";
}
}
2、编写前端页面
我们要使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<div data-th-text="${msg}"></div>
</body>
</html>
(1)开发期间模板引擎页面修改以后,要实时生效,需要修禁用hymeleaf缓存。
2)页面修改完成以后ctrl+f9:重新编译;
4、测试。成功输出
5、Thymeleaf的使用语法
控制层:
@Controller
public class IndexController {
@RequestMapping("/test")
public String Index(Model model){
model.addAttribute("msg","hello springboot");
model.addAttribute("users", Arrays.asList("spring","boot"));
return "test";
}
}
前端:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<h1>测试页面</h1>
<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>
<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签:官网#9-->
<h4 th:each="user :${users}" th:text="${user}"></h4>
<h4>
<!--行内写法:官网#12-->
<span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>