Thymeleaf 模板引擎

前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。

jsp支持非常强大的功能,包括能写Java代码,但是我们现在的这种情况:

  1. SpringBoot这个项目首先是以jar的方式,不是war。
  2. 我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。

SpringBoot推荐你可以来使用模板引擎:

模板引擎,其实jsp就是一个模板引擎,还有以用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但是他们的思想都是一样的。

看图:

springboot前端要哪些字段就返回 springboot前端用什么_java

模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些 值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引 擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们 想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只 不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介 绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他 的这个语法更简单。而且呢,功能更强大。

首先,我们来看SpringBoot里边怎么用。

引入Thymeleaf

对于springboot来说,什么事情都是一个start的事情,我们去在项目中引入一下。给大家三个网址: Thymeleaf 官网:https://www.thymeleaf.org/ Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf Spring官方文档: 找到我们对应的版本https://docs.spring.io/spring-boot/docs/2.4.5.RELEASE/reference/htmlsingle/#using-boot-starter

找到对应的pom依赖

<!--thymeleaf-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Maven会自动下载jar包

springboot前端要哪些字段就返回 springboot前端用什么_spring boot_02

thymeleaf 分析

我们已经引入了Thymeleaf,那这个要如何使用 我们首先得按照SpringBoot的自动配置原理看一下我们这个Thymeleaf的自动配置规则,在按照那个规则,我们进行使用。

我们去找一下Thymeleaf的自动配置类:ThymeleafProperties

@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
	private static final Charset DEFAULT_ENCODING;
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	public static final String DEFAULT_SUFFIX = ".html";
	private boolean checkTemplate = true;
	private boolean checkTemplateLocation = true;
	private String prefix = "classpath:/templates/";
	private String suffix = ".html";
	private String mode = "HTML";
	private Charset encoding;
}

可以在其中看到默认的前缀和后缀! 我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。 使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!

测试: 1、编写一个TestController

@Controller
public class TestController {
	@RequestMapping("/t1")
	public String test1(){
	//classpath:/templates/test.html
	return "test";
	}
}

2、编写一个测试页面 test.html 放在 templates 目录下

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<h1>测试页面</h1>
</body>
</html>

3、启动项目测试

Thymeleaf 语法学习

Thymeleaf 官网:https://www.thymeleaf.org/

Thymeleaf语法 简单的练习

1、修改测试请求,增加数据传输

@RequestMapping("/t1")
public String test1(Model model){
	//存入数据
	model.addAttribute("msg","Hello,Thymeleaf");
	//classpath:/templates/test.html
	return "test";
}

2、如果要使用thymeleaf,需要在html文件中导入命名空间的约束

xmlns:th="http://www.thymeleaf.org"

3、编写前端页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>zcm</title>
</head>
<body>
<h1>测试页面</h1>
	<!--th:text就是将div中的内容设置为它指定的值,和Vue一样-->
	<div th:text="${msg}"></div>
</body>
</html>

4、启动项目测试