(1) th:action
定义后台控制器路径,类似<form>
标签的action属性。
例如:
<form th:action="@{/test/hello}" >
<input th:type="text" th:name="id">
<button>提交</button>
</form>
(2) th:each
对象遍历,功能类似jstl中的<c:forEach>
标签。
创建com.itheima.model.User,代码如下:
public class User {
private Integer id;
private String name;
private String address;
//..get..set
}
Controller添加数据
/***
* 访问/test/hello 跳转到demo1页面
* @param model
* @return
*/
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("hello","hello welcome");
//集合数据
List<User> users = new ArrayList<User>();
users.add(new User(1,"张三","深圳"));
users.add(new User(2,"李四","北京"));
users.add(new User(3,"王五","武汉"));
model.addAttribute("users",users);
return "demo1";
}
页面输出
<table>
<tr>
<td>下标</td>
<td>编号</td>
<td>姓名</td>
<td>住址</td>
</tr>
<tr th:each="user,userStat:${users}">
<td>
下标:<span th:text="${userStat.index}"></span>,
</td>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.address}"></td>
</tr>
</table>
测试效果
(3) Map输出
后台添加Map
//Map定义
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("No","123");
dataMap.put("address","深圳");
model.addAttribute("dataMap",dataMap);
页面输出
<div th:each="map,mapStat:${dataMap}">
<div th:text="${map}"></div>
key:<span th:text="${mapStat.current.key}"></span><br/>
value:<span th:text="${mapStat.current.value}"></span><br/>
==============================================
</div>
测试效果
(4)数组输出
后台添加数组
//存储一个数组
String[] names = {"张三","李四","王五"};
model.addAttribute("names",names);
页面输出
<div th:each="nm,nmStat:${names}">
<span th:text="${nmStat.count}"></span><span th:text="${nm}"></span>
==============================================
</div>
测试效果
(5)Date输出
后台添加日期
//日期
model.addAttribute("now",new Date());
页面输出
<div>
<span th:text="${#dates.format(now,'yyyy-MM-dd hh:ss:mm')}"></span>
</div>
测试效果
(6) th:if条件
后台添加年龄
model.addAttribute("age",22);
页面输出
<div>
<span th:if="${(age>=18)}">终于长大了!</span>
</div>
测试效果
(7) th:fragment 定义一个模块
可以定义一个独立的模块,创建一个footer.html代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=charset=utf-8">
<title>fragment</title>
</head>
<body>
<div id="C" th:fragment="copy" >
关于我们<br/>
</div>
</body>
(8) th:include
可以直接引入th:fragment,在demo1.html中引入如下代码:
<div id="A" th:include="footer::copy"></div>
效果如下: