springboot加thymeleaf,实现分页查询

废话不多说,直接进入正题,我用的是jpa,前端用的bootstrap,我们直接看代码

//前端分页实现代码
<nav aria-label="Page navigation">
        <ul class="pagination">

            <li th:class="${loaclPage == 1}? 'disabled' : ''" >
//th:if若为false会隐藏该模块
                    <a  th:if="${loaclPage != 1}" th:href="@{/pageQuery(page=${loaclPage}-1)}"  aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                    <a  th:if="${loaclPage == 1}" href=#  aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>

            </li>



            <li th:each="page,iterStat:${#numbers.sequence(1,total)}" th:class="${loaclPage == page}? 'active' : ''">
                <a th:href="@{/pageQuery(page=${page})}" th:text="${page}"></a>
            </li>




            <li th:class="${loaclPage == total}? 'disabled' : ''">
                <a th:if="${loaclPage != total}" th:href="@{/pageQuery(page=${loaclPage}+1)}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
                <a th:if="${loaclPage == total}" href="#" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>

接下来看后台部分

//控制层
@RequestMapping("/pageQuery")
    public String pageList(Model model,Integer page){

        if(page==null) page=1;//若无分页参数传进,则默认指定为1

        Page<User> users=userService.getUserList(page,5);
        int counter=userService.count()/5;

        model.addAttribute("total",counter+1);//传总页数,因为int及进行除法自动砍掉末尾小数所以要进一
        model.addAttribute("loaclPage",page);//将当前页传往前端
        model.addAttribute("users",users);
        return "list";
    }

//service(dao)层
@Override
//jpa自带的count函数会返回当前table记录的总个数
    public int count() {
        return (int)userRepository.count();
    }

你可能感兴趣的:(Spring,boot)