SpringDataJPA实现分页查询,并在前端展示

前端代码:

<div class="pagelist">
	<p>当前<span th:text="${students.getNumber()} + 1"></span>页,总<span th:text="${students.totalPages}"></span>页											                 共<span th:text="${students.totalElements}"></span>条记录
		<a th:href="@{/admin/listStudent}">首页</a>
		<a th:href="@{/admin/listStudent(pageNum = ${students.hasPrevious()} ? ${students.getNumber() } : 1)}">上一页</a>
		<a th:href="@{/admin/listStudent(pageNum = ${students.hasNext()} ? ${students.getNumber()} + 2 : ${students.totalPages})}">下一页</a>
		<a th:href="@{/admin/listStudent(pageNum = ${students.totalPages})}">尾页</a>
	</p>
</div>

dao 层接口:

public interface StudentDao extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student> {
}

service层接口

Page<Student> findAll(Pageable pageable);

Service实现类

public Page<Student> findAll(Pageable pageable) {
	return studentDao.findAll(pageable);
}

controller 层:

@RequestMapping("/listStudent")
    public String listStudent(Model model, HttpServletResponse response, Integer pageNum) {
        //判断前端传递过来的pageNum是否为空
        if (pageNum == null){
            pageNum = 1;
        }
        //创建一个Pageable对象用于封装pageNUm和每页显示数据数量
        // (当前页, 每页记录数)
        Pageable pageable = PageRequest.of(pageNum - 1, ConstantUtil.PAGE_RECORD_NUM);
        //根据pageable对象查询当前登录用户的学生信息
        Page<Student> list = studentService.findAll(pageable);
        model.addAttribute("students", list);
        // 允许iframe
        response.addHeader("x-frame-options","SAMEORIGIN");
        return "/listStudent";
    }
上一篇:springDataJpa的demo


下一篇:亚里夫-量子电子学 部分习题整理