1、优点:
关于Thymeleaf的优点,我只说一条:它就是html页面
下面直接上代码
导入pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot官方文档建议在开发时将缓存关闭,那就在application.properties文件中加入下面这行(正式环境缓存还是要开启的)
spring.thymeleaf.cache=false
前台:
前端编写thymeleaf代码时容易出错,最好引入这行代码
<html xmlns:th="http://www.thymeleaf.org">
list.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf模板知识点介绍</title>
</head>
<body>
<div th:text="${msg}"></div>
<table width="60%" border="1">
<tr>
<td>id</td>
<td>用户名</td>
<td>密码</td>
</tr>
<tbody>
<tr th:each="u : ${userList}">
<td th:text="${u.uid}"></td>
<td th:text="${u.uname}"></td>
<td th:text="${u.pwd}"></td>
</tr>
</tbody>
</table>
</body>
</html>
后台代码:
User:
package com.zking.springboot01.entity;
import lombok.Data;
import lombok.ToString;
@Data
public class User {
private Integer uid;
private String uname;
private String pwd;
public User(){
}
public User(Integer uid,String uname,String pwd){
this.uid = uid;
this.uname = uname;
this.pwd = pwd;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
UserController:
package com.zking.springboot01.controller;
import com.zking.springboot01.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/thymeleaf")
public class UserController {
@RequestMapping("/list")
public String hello(HttpServletRequest request){
/*
* 1、获取单个值
* 2、能够在html界面进行遍历展示
* 3、如何在HTML页面转义html代码块
* */
request.setAttribute("msg", "传递单个数据");
List<User> userList = new ArrayList<>();
userList.add(new User(1, "zs", "123"));
userList.add(new User(2, "ls", "234"));
userList.add(new User(3, "ww", "345"));
request.setAttribute("userList", userList);
request.setAttribute("htmlStr", "<span style='color:red'>页面转义html代码块<span>");
return "list";
}
}
运行结果:
遍历结果: