Springboot整合Thymeleaf使用Datatable利用AJAX进行页面的查询功能完整实现
以下是一个简化的Spring Boot整合Thymeleaf使用DataTables和AJAX进行页面查询功能的代码示例:
<!-- index.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>DataTable Example</title>
<link th:href="@{/css/datatable.css}" rel="stylesheet"/>
<script th:src="@{/js/datatable.js}"></script>
</head>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
<script type="text/javascript" th:inline="javascript">
$(document).ready(function() {
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": /*[[@{/data}]]*/,
"type": "POST"
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "age" },
{ "data": "start_date" },
{ "data": "salary" }
]
});
});
</script>
</body>
</html>
// DataTableController.java
@Controller
public class DataTableController {
@Autowired
private DataTableService dataTableService;
@PostMapping("/data")
@ResponseBody
public DataTableOutput handleDataTableRequest(@RequestBody DataTablesInput input) {
return dataTableService.buildDataTableOutput(input);
}
}
// DataTableService.java
@Service
public class DataTableService {
@Autowired
private YourEntityRepository yourEntityRepository;
public DataTableOutput buildDataTableOutput(DataTablesInput input) {
List<YourEntity> data = yourEntityRepository.findAll((Root<YourEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
// 这里应该是构建特定的查询条件
return null;
}, new PageRequest(input.getStart()/input.getLength(), input.getLength(),
new Sort(Direction.ASC, "id"))); // 假设按id排序
long count = yourEntityRepository.count();
return new DataTableOutput(count, data);
}
}
// DataTableOutput.java
public class DataTableOutput {
private long recordsTotal;
private long recordsFiltered;
private List<YourEntity> data;
// 构造函数、getter和sett
评论已关闭