背景:SpringBoot的项目是嵌入Tomcat然后打成jar包的形式直接使用的,不是打成war包放在Tomcat上面运行的。所以是不至此JSP的
解决:SpringBoot推荐使用thymeleaf模板引擎
模板引擎:参见的模板引擎有:JSP、Velocity、Freemarker、Thymeleaf,
作用:我们建好模板,把模板和数据交给引擎,引擎根据你的模板和数据生产页面,这样就实现了页面的动态生成
thymeleaf引擎的使用
第一步:打开SpringBoot的指导文档的Starter,在里面找到thymeleaf的pom,然后填写依赖到项目的pom文件里面
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二步:把做好的html页面放到"classpath:/templates/"
这一步可以打开ThymeleafAutoConfiguration类然后在里面找到ThymeleafProperties这里类,从里面可以看到如下路径。
这个路径默认存放模板,thymeleaf引擎扫描的文件夹路径
public static final String DEFAULT_PREFIX = "classpath:/templates/";
第三步:按照thymeleaf的要求把数据存入和选择数据对应模板,如下例子,在Contoller类中编写
@RequestMapping("/success")
public String success(Map<String,Object> map){
//默认数据会被放在请求域中
map.put("hello","<h1>你好</h1>");
map.put("users", Arrays.asList("张三","李四" ,"王五"));
return "success";
}
第四步:编写thymeleaf的模板,如下面的例子(和jsp有点像)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="shortcut icon" href="/fanren/favicon.ico" th:href="@{/favicon.ico}" >
</head>
<body>
<h1>成功!</h1>
<!--th:text 将div里面的文本内容设置为-->
<div th:text="${hello}">这是显示欢迎信息</div>
<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>
<!--th:each每次遍历都会生成当前这个标签-->
<h4 th:text="${user}" th:each="user :${users}"></h4>
<hr/>
<h4>
<span th:each="user :${users}">[[${user}]]</span>
</h4>
</body>
</html>
编写的时候导入名称空间,要不然就没有提示了,还有如果不经过模板引擎浏览器直接访问的话会默认现实标签里面的内容