本章练习springboot引入模板引擎Thymeleaf
这对于我来说是新知识,从一开始对Java模板引擎的一脸茫然,到查阅资料后的大致了解。网上有说Thymeleaf是jsp的大哥。
实现目标:搭建项目建立HTML页面,使用thymeleaf标签显示数据。
目录结构:
properties配置
spring.thymeleaf.prefix=classpath:/templates/user/
spring.thymeleaf.suffix=.html
pom.xml加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
controller
@RequestMapping("/test01")
public String test01(Model model){
People people=new People();
people.setAge(12);
people.setName("普京");
People people2=new People();
people2.setAge(122);
people2.setName("普京2");
List<People> list=new ArrayList<People>();
list.add(people);
list.add(people2);
System.out.println("xianxian");
model.addAttribute("li","lizhonghua");
model.addAttribute("people",people);
model.addAttribute("list", list);
model.addAttribute("panduan","判断");
return "helloThymeleaf";
}
HTML页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello LiZhongHua</h1>
<br>
<input type="text" value="哈哈">
<label>白宫一把手</label>
<p th:text="哈哈力争"></p>
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
<tr>
<td th:text="${people.name}"></td>
<td th:text="${people.age}"></td>
</tr>
<h1>------------------------------------------</h1>
<tr th:each="each,list:${list}">
<td th:text="${each.name}"></td>
<td th:text="${each.age}"></td>
</tr>
</table>
<h2>=================================================</h2>
<!-- 条件判断,if和unless 条件一致,情况不同显示不同的文本 -->
<span th:if="${panduan=='判断'}" th:text="判断了"></span>
<span th:unless="${panduan == '判断'}" th:text="ggggggggggggggg"></span>
<h2>==================================================</h2>
<!-- 字符串拼接,用|变量、文本| -->
<p th:text="|${panduan },welcome.|"></p>
</body>
</html
浏览器访问 http://localhost:8080/test01
个人认为:这个模板引擎对于现在的我来说用处不大,暂且接触不到。还要以jsp为主,多搞多锻炼