springboot是通过jar包的方式打包数据,不是war包,而且是嵌入式的tomcat,不支持jsp页面,但我们不能通过静态页面来写项目,我们的后台传过来的数据就不能c:forch,c:if等进行数据处理
模板引擎:jsp、velocity、Freemaker、Thymeleaf
虽然种类很多,但是他们的工作原理是一样的,都是讲模板和数据整合,通过模板引擎进行处理后输出到页面。
springboot推荐使用Thymeleaf:语法简单,功能强大;
<!--引入模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
通过在properties中设置thymeleaf的版本号:
<properties>
<java.version>1.8</java.version>
<!--修改thymeleaf版本-->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
注意:thymeleaf和lyout的版本要对应,可以去github中查找thymeleaf-layout-dialect来获取版本的信息
2,thymeleaf的语法
使用:
第一步:在html导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
后台的数据传递:例如我们使用一个map传递的方式
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "hello";
}
@RequestMapping("/success")
public String Success(Map<String,Object> map){
map.put("hello","控制类:你好");
return "success";
}
}
<div th:text="${hello}">
</div>
th:任意html属性值替换原生的html属性
例如:th:class="myClass" th:id="myDiv",这样就可以替换原生的html的标签属性。我想此处肯定能给大家在动态绑定中能有启发。
这里展示一下,th的整体语法:
2表达式,常用的语法有$()和*()
具体实例:
1.此时的hello里面含有h1标签,使用th:text会将h1标签转义,而th:utext就不会转义
2.将users遍历后,遍历的标签自身也会被复制多次h4会重复三次,span也会重复三次
3.如果要在标签内直接写入结果,可以使用[[]]或者[()]的形式,区别就是前者转义后者不转义
@RequestMapping("/success")
public String Success(Map<String,Object> map){
map.put("hello","控制类:<h1>你好</h1>");
map.put("users", Arrays.asList("zhangsan","lisi","王五"));
return "success";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
成功
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<h4 th:text="${user}" th:each="user:${users}"></h4>
<h4>
<span th:each="user : ${users}">[[${user}]]</span>
</h4>
</body>
</html>
运行结果如下: