现在比较流行前后端分离开发,但在有些业务场景下模板引擎也用的不少。本文介绍thymeleaf页面的局部更新,Spring Boot采用的是2.0.4,先来看代码。
IndexController.java:
package com.example.demo.thymeleaf;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/refresh")
public class IndexController {
@RequestMapping
public String globalRefresh(Model model) {
List<Map<String,String>> lists = new ArrayList<>();
Map<String,String> map = new HashMap<>();
map.put("author", "曹雪芹");
map.put("title", "《红楼梦》");
map.put("url", "www.baidu.com");
lists.add(map);
// 用作对照
model.addAttribute("refresh", "我不会被刷新");
model.addAttribute("title", "我的书单");
model.addAttribute("books", lists);
return "test";
}
/**
* 局部刷新,注意返回值
* @param model
* @return
*/
@RequestMapping("/local")
public String localRefresh(Model model) {
List<Map<String,String>> lists = new ArrayList<>();
Map<String,String> map = new HashMap<>();
map.put("author", "罗贯中");
map.put("title", "《三国演义》");
map.put("url", "www.baidu.com");
lists.add(map);
model.addAttribute("title", "我的书单");
model.addAttribute("books", lists);
// "test"是test.html的名,
// "table_refresh"是test.html中需要刷新的部分标志,
// 在标签里加入:th:fragment="table_refresh"
return "test::table_refresh";
}
}
test.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>thymeleaf局部刷新</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
<div>
<span style="margin:0 auto;font-size: 26px" th:text="${refresh}"></span>
<button onClick="localRefresh()">点击刷新表格</button>
</div>
<!-- 需要局部刷新的部分,设置了th:fragment="table_refresh" -->
<div id="table_refresh" style="text-align: center;margin:0 auto;width: 900px" th:fragment="table_refresh">
<h1 th:text="${title}"></h1>
<table width="100%" border="1" cellspacing="1" cellpadding="0">
<tr>
<td>Author</td>
<td>Book</td>
<td>Url</td>
</tr>
<tr th:each="book : ${books}">
<td th:text="${book.author}"></td>
<td th:text="${book.title}"></td>
<td th:text="${book.url}"></td>
</tr>
</table>
</div>
</body>
<script>
function localRefresh() {
// 装载局部刷新返回的页面
$('#table_refresh').load("/refresh/local");
}
</script>
</html>
页面引入了jquery,运行后页面内容如下: 点击“点击刷新表格”后页面如下: $('#table_refresh').load("/refresh/local")这行代码即异步请求局部的页面,调用它返回的结果如下:
只返回了我们在页面中设置了th:fragment="table_refresh"部分,就实现了局部刷新。