SpringBoot学习目录
1. 模板引擎
为什么使用模板引擎,这是由于在SpringBoot中内置了Tomcat,但是这个Tomcat并不支持Jsp,所以为了让普通的HTML也可以接受到SpringBoot中后端传出来的数据,所以需要使用到模板引擎;
在官方文档中有一些启动器,通过这些启动器进行模板的引入;比如:
2. 如何在SpringBoot中使用模板引擎
Thymeleaf的作用和SpringMVC中视图解析器作用类似;
1. 按照上面的方法先写启动器
(这里以thymeleaf为例)
<!--导入启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果想要修改版本的话,就只需要在properties标签里面添加<thymeleaf.version>和<thymeleaf-layout-dialect.version>,然后在其中设置好版本号就可以了,但是两个版本必须要适配,一般是thymeleaf版本为3的时候适配thymeleaf-layout版本为2;
2.导入Thymeleaf的名称空间
<html xmlns:th="http://www.thymeleaf.org">
但是上面的语句在官方文档里面是这么说的:which has no influence at all in template processing,
意思是在整个模板的进程中是没有任何的影响的;纯粹就是为了给自己没有一个名称空间做的补充;
3. 在controller写业务和返回的页面
@Controller//别用@RestController,否则就给你返回一个字符串
public class JunpController {
@RequestMapping("/jump")
public String JumpTest(){
return "success";
}
}
再次记录@ResponseBody和@Controller合成了@RestController,一旦使用@RestController就没办法通过视图解析器合成文件;
4. 在templates目录下创建需要的HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试跳转</title>
</head>
<body>
<h1>跳转成功!</h1>
</body>
</html>
大致模板使用就是如此,至于模板的用法,那就照着官方文档,面向百度吧;
最后记录一下:这个模板可以使用的部分操作
#将键为user的值直接用这个标签显示;比如user值为user,则等价于
#<h1>user<h1>
<h1 th:text="${user}"><h1>
#如果是一个数组,则可以用th:echo,
#下面语句会产生三个<td>;he就是这里赋值,使用方式像是foreach
<td th:text="${he}" th:each="he:${hello}"></td>