Springbooot实现数据查询分页功能

1.效果展示

2.先建一个Condition类

@Data
public class Condition {
    //查询搜索条件
    private String title;
    private int categoryId;
    //当前页码
    private int pageIndex;
    //每一页条目数
    private int pageCount;
//#{offset} 表示查询的起始位置
private int offset;
    public Condition(int pageIndex, int pageCount) {
        this.pageIndex = pageIndex;
        this.pageCount = pageCount;
    }

3.mapperce层接口及实现

// 查询总数
List<AdvInfo> findByCondition(Condition condition);
// 查询出数据
 List<AdvInfo> findByAdvAll(Condition condition);
    <select id="countByInfoAll" resultType="int" >
        select count(*) from advinfo
    </select>

    <select id="findByCondition" resultMap="adInfoMap"  parameterType="Condition">
        SELECT * FROM advinfo
        WHERE advTitle LIKE CONCAT('%', #{title}, '%') AND categoryId = #{categoryId}
            LIMIT #{offset}, #{pageCount}
    </select>

4.service层

 @Override
    public PageResult<AdvInfo> findByAdvAll(Condition condition) {
        int totalItems=advInfoMapper.countByInfoAll();
        int totalPages=(int)Math.ceil((double)totalItems/condition.getPageCount());
        List<AdvInfo> data=advInfoMapper.findByAdvAll(condition);
        PageResult<AdvInfo> pageResult = new PageResult<>();
        pageResult.setData(data);
        pageResult.setCurrentPage(condition.getPageIndex());
        pageResult.setTotalPages(totalPages);
        pageResult.setTotalItems(totalItems);
        return pageResult;
    }

5.controller层:

 @RequestMapping("advInfo.action")
    public Map<String, Object> method15(Condition condition, String categoryName, HttpServletRequest request) throws Exception {
        System.out.println("当前页码"+condition.getPageIndex());
      int  offset=(condition.getPageIndex()-1)*condition.getPageCount();
        condition.setOffset(offset);
        Map<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user);
        System.out.println("456+++++++++" + user);
        map.put("user", user);
        if (condition.getTitle() != "" && categoryName != "用户未选择") {
            int i = advService.queryIdByName(categoryName);
            condition.setCategoryId(i);
            PageResult<AdvInfo> byAdvAll = advService.findPagenated(condition);
            List<AdvInfo> advInfoList = byAdvAll.getData();
            //一个map就等同与一个json对象
            map.put("advInfoList", advInfoList); // 存储广告列表
            map.put("currentPage", byAdvAll.getCurrentPage());
            map.put("totalPages", byAdvAll.getTotalPages());
            map.put("totalItems", byAdvAll.getTotalItems());
        } else {
            PageResult<AdvInfo> byAdvAll = advService.findByAdvAll(condition);
            List<AdvInfo> advInfoList = byAdvAll.getData();
            //一个map就等同与一个json对象
            map.put("advInfoList", advInfoList); // 存储广告列表
            map.put("currentPage", byAdvAll.getCurrentPage());
            map.put("totalPages", byAdvAll.getTotalPages());
            map.put("totalItems", byAdvAll.getTotalItems());
        }
        return map;
    }

5.查询所有页面:

表单:

<form  method="post" id="sreachForm">
    <label>广告分类:</label>
    <select id="category" name="categoryName">
        <option value="用户未选择">请选择</option>
        <option value="电子产品">电子产品</option>
        <option value="汽车">汽车</option>
        <option value="房地产">房地产</option>
    </select><br>
    <label>广告标题:</label>
    <input type="text" id="title" name="title">
    <p><input type="button" id="search" value="检索"/></p>
    <p><input type="button" id="selectAll" value="返回首页"/></p>
</form>

导航按钮:

<div>
    <button id="prevPage">上一页</button>
    <span id="pageInfo"></span>
    <div id="pages"></div>
    <button id="nextPage">下一页</button>
</div>

js实现:

1.先页面初始化:currentPage = 1,总页数从controller层获得;

  <script type="text/javascript" src="js/jquery-2.1.0.min.js"></script>
    <script type="text/javascript">
        $(function () {
            let currentPage = 1;
            let totalPages;
            loadAdvInfo(currentPage);
            function loadAdvInfo(pageIndex) {
                console.log("loadAdvInfo运行,页码:" + pageIndex)
            var categoryName=$("#category").val();
                var title=$("#title").val();
                $.ajax({
                    url: "advInfo.action",
                    type: "get",
                    data: {
                        categoryName:categoryName,
                        title:title,
                        pageIndex: pageIndex,
                        pageCount: 5// 假设每页5条数据
                    },
                    success: function (data) {
                        $('#userInfo').text(data.user.name);
                        var elementById = document.getElementById("im");
                        elementById.setAttribute('src',data.user.url);
                        var myTbody = document.getElementById("myTbody");
                        myTbody.innerHTML = "";
                        for (var i = 0; i < data.advInfoList.length; i++) {
                            var advjson = data.advInfoList[i];
                            addRow(advjson);
                        }
                        totalPages = data.totalPages; // 更新总页数
                        updatePagination();
                    },
                    error: function () {
                        alert("加载失败")
                    },
                    dataType: "json"
                });
            }

上一页和下一页以及页码功能的实现关键点:

  1. 变量定义
    • currentPage:用于存储当前页码。
    • totalPages:用于存储总页数。
  1. 初始化
    • 页面加载完成后,通过loadAdvInfo函数加载第一页的数据,并初始化currentPage为1。
  1. 加载广告信息
    • loadAdvInfo函数通过AJAX请求从服务器获取数据,并将数据显示在表格中。同时更新totalPages
  1. 分页逻辑
    • 上一页按钮:如果当前页码大于1,则按钮可用,并绑定点击事件来加载上一页的数据(通过currentPage--实现页码的减少)。
    • 下一页按钮:如果当前页码小于总页数,则按钮可用,并绑定点击事件来加载下一页的数据(通过currentPage++实现页码的增加)。
  1. 页码显示与跳转
    • 页码信息显示pageInfo元素用于显示当前页码和总页数。
    • 页码按钮生成:通过循环生成页码按钮,并绑定点击事件,点击时设置currentPage为对应的页码,并重新加载广告信息。
function updatePagination() {
                var prevButton = document.getElementById('prevPage');
                var nextButton = document.getElementById('nextPage');
                var pageInfo = document.getElementById('pageInfo');

                // 设置上一页按钮状态
                if (currentPage > 1) {
                    prevButton.disabled = false; // 确保按钮可用
                    prevButton.onclick = function () { // 设置点击事件
                        currentPage--; // 当前页码减一
                        loadAdvInfo(currentPage); // 加载上一页的数据
                    };
                } else {
                    prevButton.disabled = true; // 如果已经是第一页,禁用按钮
                }

                // 设置下一页按钮状态
                if (currentPage < totalPages) {
                    nextButton.disabled = false; // 确保按钮可用
                    nextButton.onclick = function () { // 设置点击事件
                        currentPage++; // 当前页码加一
                        loadAdvInfo(currentPage); // 加载下一页的数据
                    };
                } else {
                    nextButton.disabled = true; // 如果已经是最后一页,禁用按钮
                }
                // 更新页面信息
                pageInfo.innerText = "当前页: " + currentPage + " / 总页数: " + totalPages;

                // 清除现有的页数链接
                var pagesDiv = document.getElementById('pages');
                pagesDiv.innerHTML = '';

                // 生成新的页数链接
                for (var i = 1; i <= totalPages; i++) {
                    var pageLink = document.createElement('button');
                    pageLink.innerText = i;
                    pageLink.className = 'page-link';
                    if (i === currentPage) {
                        pageLink.disabled = true; // 当前页码的按钮应被禁用
                    }
                    pageLink.onclick = function () {
                        currentPage = parseInt(this.innerText);
                        loadAdvInfo(currentPage);
                    };
                    pagesDiv.appendChild(pageLink);
                }
            }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值