模板技术
在springboot中不会使用jsp,而是使用模板技术,因为模板技术显示的更快。
模板技术分为三类:velocity,freemarker,thymeleaf。
Thymleaf是springboot官方推荐的模板技术。
配置环境:
- 添加依赖(热部署 lombok web thymeleaf )
- 添加配置
thymeleaf: prefix: classpath:/templates 模板文件的位置 suffix: .html 默认模板文件后缀 mode: HTML5 默认文件类型 encoding: UTF-8 文件编码 cache: false 是否开启缓存
-
创建一个h5文件,并添加命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
- 写一个Controller
@GetMapping("/test01") public ModelAndView test01(ModelAndView mv){ mv.setViewName("index"); return mv; }
内容:
1.显示文字
<p th:text="thymeleaf !!!"></p>
<p th:text="2019+10"></p>
2.显示变量
mv.addObject("name","<b>zhangsan</b>");
<p th:text="${name}"></p>
<p th:utext="${name}"></p>
3.显示日期
mv.addObject("today",new Date());
<h5 th:text="${#calendars.format(today,'yyyy-MM-dd')}"></h5>
4.显示对象
User user = new User("zhangsan",20);
mv.addObject("user",user);
<div th:object="${user}">
<p th:text="*{name}"></p>
<p th:text="*{age}"></p>
</div>
5.输入url
mv.addObject("id",2);
<div>
<a href="" th:href="@{'/user/list'}">显示全部</a>
<a href="" th:href="@{/user(id=${id})}">查看id是2的数据</a>
<a href="" th:href="@{'/user/'+${id}}">查看id是2的数据</a>
</div>
6.if判断
mv.addObject("isAdmin",true);
<div th:if="${isAdmin}==true">
我是管理员
</div>
<div th:if="${isAdmin}==false">
我不是管理员
</div>
7.switch判断
mv.addObject("role","teacher");
<div th:switch="${role}">
<p th:case="student">我是学生</p>
<p th:case="teacher">我是老师</p>
</div>
8.循环显示
List<User> users = new ArrayList<User>();
for(int i=1;i<5;i++){
User u = new User("li"+i,i);
users.add(u);
}
mv.addObject("users",users);
<ul th:each="user,index:${users}">
<li th:class="${index.even}?'blue':'red'">
<span th:text="${user.name}"></span>
<span th:text="${user.age}"></span>
</li>
</ul>
9.下拉框
<select name="" id="">
<option value="">请选择用户</option>
<option th:each="list:${users}" th:text="${list.name}" th:value="${list.name}"></option>
</select>
10.form提交
User user = new User("zhangsan",20);
mv.addObject("user",user);
<form th:action="@{/addUser}" th:object="${user}" th:method="post">
<input type="text" th:field="*{name}" >
<input type="text" th:field="*{age}" >
<input type="submit" >
</form>
@PostMapping("/addUser")
public String addUser(@ModelAttribute User user){
System.out.println(user);
return "success";
}
11.引入代码
Head.html
<div th:fragment="begin">
begin~~~~~
</div>
<div id="end">
end~~~~~~~
</div>
<div th:insert="~{head::begin}"></div>
body~~~
<div th:insert="~{head::#end}"></div>