Spring MVC页面如何每5秒拉取数据库数据并刷新表格?
问题描述
我有一个基于Spring MVC的表格展示需求,现有代码如下,想实现每5秒自动拉取数据库数据并刷新表格内容:
Controller 代码
@Controller public class FileImportsController { private EntityImportRequestsService entityImportRequestsService; @Autowired public FileImportsController(EntityImportRequestsService entityImportRequestsService) { this.entityImportRequestsService = entityImportRequestsService; } @GetMapping("/imported_files") public String viewHomePage(Model model) { List<EntityImportRequestsTable> listProducts = entityImportRequestsService.findAll(); model.addAttribute("listProducts", listProducts); return "index"; } }
页面代码(Thymeleaf)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <title>Product Manager</title> </head> <body> <div align="center"> <h1>Product List</h1> <table border="1" cellpadding="10"> <thead> <tr> <th>Product ID</th> <th>Name</th> <th>Brand</th> <th>Made In</th> <th>Price</th> </tr> </thead> <tbody> <tr th:each="product : ${listProducts}"> <td th:text="${product.requestId}">Product ID</td> <td th:text="${product.name}">Name</td> <td th:text="${product.brand}">Brand</td> <td th:text="${product.madein}">Made in</td> <td th:text="${product.price}">Price</td> </tr> </tbody> </table> </div> </body> </html>
实现步骤
1. 新增后端JSON数据接口
在现有FileImportsController中添加一个专门返回数据的接口,供前端异步拉取:
@GetMapping("/imported_files/data") @ResponseBody public List<EntityImportRequestsTable> getImportedFilesData() { return entityImportRequestsService.findAll(); }
注意:确保
EntityImportRequestsTable类实现Serializable接口,Spring会自动将对象序列化为JSON格式。
2. 修改前端实现自动刷新
在页面的<body>末尾添加JavaScript代码,实现定时拉取数据并更新表格:
// 定义刷新表格的核心函数 function refreshTable() { fetch('/imported_files/data') .then(response => response.json()) .then(data => { const tbody = document.querySelector('table tbody'); // 清空原有表格内容 tbody.innerHTML = ''; // 遍历新数据生成表格行 data.forEach(product => { const row = document.createElement('tr'); row.innerHTML = ` <td>${product.requestId}</td> <td>${product.name}</td> <td>${product.brand}</td> <td>${product.madein}</td> <td>${product.price}</td> `; tbody.appendChild(row); }); }) .catch(error => console.error('数据刷新失败:', error)); } // 页面加载完成后立即刷新一次,之后每5秒执行一次 window.onload = function() { refreshTable(); setInterval(refreshTable, 5000); // 5000毫秒 = 5秒 };
可选优化:避免重复请求叠加
如果担心网络延迟导致多个请求同时进行,可以添加状态锁:
let isRefreshing = false; function refreshTable() { if (isRefreshing) return; isRefreshing = true; fetch('/imported_files/data') .then(response => response.json()) .then(data => { const tbody = document.querySelector('table tbody'); tbody.innerHTML = ''; data.forEach(product => { const row = document.createElement('tr'); row.innerHTML = ` <td>${product.requestId}</td> <td>${product.name}</td> <td>${product.brand}</td> <td>${product.madein}</td> <td>${product.price}</td> `; tbody.appendChild(row); }); }) .catch(error => console.error('数据刷新失败:', error)) .finally(() => { isRefreshing = false; }); } window.onload = function() { refreshTable(); setInterval(refreshTable, 5000); };
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

