springboot整合layui实现数据表格的分页操作
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
在Spring Boot中,你可以使用Layui的数据表格(DataTable)组件进行分页操作。以下是一个简单的例子,展示了如何在Spring Boot后端使用MyBatis或JPA等ORM框架,与前端Layui进行数据的分页交互。
后端(Spring Boot + MyBatis):
@RestController
@RequestMapping("/api")
public class DataController {
@Autowired
private DataService dataService;
@GetMapping("/data")
public ResponseEntity<Map<String, Object>> getData(@RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "limit", defaultValue = "10") int limit) {
Map<String, Object> result = new HashMap<>();
List<Data> dataList = dataService.findPagedData((page - 1) * limit, limit);
long total = dataService.countData();
result.put("code", 0);
result.put("msg", "");
result.put("count", total);
result.put("data", dataList);
return ResponseEntity.ok(result);
}
}
@Service
public class DataService {
@Autowired
private DataMapper dataMapper;
public List<Data> findPagedData(int offset, int limit) {
return dataMapper.selectByPage(offset, limit);
}
public long countData() {
return dataMapper.count();
}
}
前端(HTML + Layui):
<!DOCTYPE html>
<html>
<head>
<title>Data Table Example</title>
<link rel="stylesheet" href="path/to/layui/css/layui.css">
</head>
<body>
<table id="data-table" lay-filter="data-table"></table>
<script src="path/to/layui/layui.js"></script>
<script>
layui.use(['table'], function(){
var table = layui.table;
table.render({
elem: '#data-table',
url: '/api/data', // 后端分页接口
page: true, // 开启分页
limits: [10, 20, 30, 40, 50],
limit: 10 // 每页默认显示的数量
cols: [[
{field: 'id', title: 'ID', width: 80, sort: true},
{field: 'name', title: 'Name', width: 80},
// ... 其他字段
]]
});
});
</script>
</body>
</html>
在这个例子中,前端Layui数据表格组件通过table.render
方法初始化,并指定了URL为后端的分页接口/api/data
。当用户翻页时,Layui会向后端发送带有page
和limit
参数的请求,后端Spring Boot应用通过@GetMapping("/data")
接收请求,并处理分页逻辑,最终将数据以Layui要求的格式返回给前端。
评论已关闭