分页是常见的数据展示的方式。实现分页的方法是很多的,比如可以一次性查出所有数据存放在一个容器中(比如List),然后用List的sublist()实现切片操作。但是这种方法对于大量的数据就很不合适。这里总结一种只返部分信息的方法。本质是构造SQL语句。
核心的查询语句是这样的:
select * from tables limit m,n;
其中m表示从第几条数据开始(0表示的是第一条记录号),n表示查询的数据的条数。因此我们就可以利用这条语句,将n作为一页中最大的记录数,只需从前端接受需要查询的页号,将页号转化成该页第一条的记录号,就可以简单的实现啦。
Maaper:
@Repository
@Mapper
public interface QuestionMapper {
//注意这里curIndex是记录号而不是页号
@Select("select * from question limit #{curIndex},4")
List<Question>query(Map<String,Object>data);
//得到记录的总条数
@Select("select count(*) from question")
int getTotalNum();
}
Service:
@Service
public class QuestionService {
@Autowired
QuestionMapper mapper;
public List<Question>query(int curPage){
//接受的参数是页号,这里需要转化成记录号
int curIndex = (curPage-1)*4;
Map<String,Object>data = new HashMap<>();
data.put("curIndex",curIndex);
return mapper.query(data);
}
public int getTotalNums(){
return mapper.getTotalNum();
}
}
Control
@Controller
public class QuestionControl {
@Autowired
QuestionService service;
//接受的是前端传过来的页号
@RequestMapping("/list/{curPage}")
public ModelAndView query(@PathVariable int curPage){
ModelAndView mav = new ModelAndView();
mav.addObject("list",service.query(curPage));
mav.addObject("total",service.getTotalNums()/4);
mav.addObject("now",curPage);
mav.setViewName("index");
return mav;
}
}
前端Demo
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<th>问题编号</th>
<th>主题</th>
<th>内容</th>
</tr>
<tr th:each="item: ${list}">
<td th:text="${item.getQuestion_id()}"></td>
<td th:text="${item.getQuestion_title()}"></td>
<td th:text="${item.getContent()}"></td>
</tr>
</table>
<span id ="now" th:text="${now}"></span> / <span id="total" th:text="${total}"></span>
<button id="pre">上一页</button>
<button id="nex">下一页</button>
</body>
<script type="text/javascript">
$(function(){
$(document).on("click","#pre",function () {
// 获得当前的页码
var index = parseInt($("#now").text());
if (index === 1) {
alert("前面没有啦!");
} else {
//发送查询请求
index -= 1;
window.open("/list/" + index, "_self");
}
});
$(document).on("click","#nex",function () {
var index = parseInt($("#now").text());
var total = parseInt($("#total").text());
if(index === total){
alert("后面没有啦!")
}else{
index += 1;
window.open("/list/"+index,"_self");
}
});
})
</script>
</html>
效果